简体   繁体   English

Swift 5:将label的背景圈变小

[英]Swift 5: Make the background circle of the label smaller

I want the rounded edge of the label to be smaller.我希望 label 的圆边更小。

I managed to round the label, but when I want to make the circle smaller, I can't do it.我设法把label圆了,但是当我想把圆变小的时候,我做不到。

在此处输入图像描述

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.您在 label 上绘制圆圈的方式是更改标签层的背景颜色和圆角半径。 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.)您应该向视图添加 AutoLayout 约束以将其高度和宽度设置为您想要的值(实际上我会创建一个将宽度设置为给定值的约束,然后创建第二个将高度设置为等于宽度的约束,所以您只需指定一个值,并始终得到一个正方形边界矩形和一个圆形而不是椭圆形。)

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.您还可以将标签的背景设置为透明,并在视图层下添加一个新的 CAShapeLayer,其大小小于视图,但是如果视图的大小发生变化,您将需要自定义代码来更新背景层的大小。

You can change the bounds of the label, which will reduce the size of the background circle:您可以更改 label 的边界,这将减小背景圆的大小:

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.或者,如果您在故事板中创建 UILabel,请调整宽度和高度约束,保持字体大小不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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