如何在 Xcode 7 和 Swift 2 中创建圆角矩形标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31846476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a rounded rectangle label in Xcode 7 and Swift 2
提问by Michael Montella
I am working in Xcode 7 beta 3. I want to create a label with a rounded rectangle background. By default, I can create a background with my color of choice but I can't round the corners. I have tried creating an outlet for that label and then in viewDidLoad()
I wrote this code label.layer.cornerRadius = 10
. I didn't get any errors but it didn't change the label in the simulator. Does anyone know how to do this in Swift 2?
我在 Xcode 7 beta 3 中工作。我想创建一个带有圆角矩形背景的标签。默认情况下,我可以使用我选择的颜色创建背景,但不能圆角。我曾尝试为该标签创建一个插座,然后在其中viewDidLoad()
编写了此代码label.layer.cornerRadius = 10
。我没有收到任何错误,但它没有更改模拟器中的标签。有谁知道如何在 Swift 2 中做到这一点?
回答by Laky
回答by Fred Faust
You'll also want to clip to bounds of the label:
您还需要剪辑到标签的边界:
myLabel.backgroundColor = UIColor.blueColor()
myLabel.layer.cornerRadius = 10.0
myLabel.clipsToBounds = true
回答by Aladin
A view can optionally limit the drawing of its subviews so that any parts of them outside the view are not shown. This is called clippingand is set with the view's
clipsToBounds
property.
视图可以选择性地限制其子视图的绘制,以便不显示视图外的任何部分。这称为裁剪,并使用视图的
clipsToBounds
属性进行设置。
So you need to add:
所以你需要添加:
label.clipsToBounds = true
result (Swift 2.0 Xcode 7 iOS9):
结果(Swift 2.0 Xcode 7 iOS9):