Home > other >  Swift 5: Make the background circle of the label smaller
Swift 5: Make the background circle of the label smaller

Time:04-01

I want the rounded edge of the label to be smaller.

I managed to round the label, but when I want to make the circle smaller, I can't do it.

enter image description here

This is my code:

dayLabel.backgroundColor = .orange
dayLabel.layer.cornerRadius = dayLabel.bounds.width / 2
dayLabel.layer.masksToBounds = true

CodePudding user response:

The way you are drawing the circle on your label is to change the background color and corner radius of the label's layer. The size of the circle will always be the size of the view.

You should add AutoLayout constraints to the view to set it's height and width to your desired value (Actually I'd create one constraint that sets the width to a given value, and then a second constraint that sets the height equal to the width, so you only need to specify a single value and always get a square bounding rectangle and a circle rather than an oval.)

Once you do that, simply use a smaller width value to make your label's background circle smaller.

Note that you will need to update your layer's corner radius when your label's layout changes or it may use the wrong cornerRadius value.

You could also set your label's background to transparent, and add a new CAShapeLayer under your view's layer and size that smaller than the view, but then you would need custom code to update the background layer's size if the view's size changes.

CodePudding user response:

You can change the bounds of the label, which will reduce the size of the background circle:

dayLabel.bounds = CGRect(x: dayLabel.bounds.minX, y: dayLabel.bounds.minY, width: 20, height: 20) //change these values to match your needs
dayLabel.textAlignment.center //to make sure the text stays centered

Or, if you're creating the UILabel in storyboards, adjust the width and height constraints, keeping the font size the same.

  • Related