简体   繁体   中英

Swift 5: Make the background circle of the label smaller

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.

在此处输入图像描述

This is my code:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM