@IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc
override func viewDidLoad() {
super.viewDidLoad()
//Make sure the width and height are same
self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
self.theImage.layer.borderWidth = 2.0
self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
self.theImage.clipsToBounds = true
}
如果你想通过情节串连图板得到 UI 对象的圆角(UILabel,UIView,UIButton,UIImageView) ,那么设置 clip to bounds true 并设置 User Defined Runtime Attributes键路径为
layer.cornerRadius,type = Number and value = 9(根据您的要求)
// extension Class
extension UILabel {
// extension user defined Method
func setRoundEdge() {
let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
//Width of border
self.layer.borderWidth = 1.0
//How much the edge to be rounded
self.layer.cornerRadius = 5.0
// following properties are optional
//color for border
self.layer.borderColor = myGreenColor.cgColor
//color for text
self.textColor = UIColor.red
// Mask the bound
self.layer.masksToBounds = true
//clip the pixel contents
self.clipsToBounds = true
}
}
产出:
为什么使用扩展方法?
创建一个 Swift 文件并添加以下代码,该代码在“ UILabel”类中使用了 Extended 方法,这个方法是用户定义的,但是可以用于应用程序中的所有标签,并且有助于保持一致性和清晰的代码,如果你将来改变任何样式只需要在扩展方法中使用。