自定义控件设置属性并实时展现并预览在xib中

关键字:

// @IBDesignable:实时看到xib设置后的效果

// @IBInspectable:给xib提供设置属性,可以xib中看到此属性

场景:

自定义一个UITextField,并提供borderColor、borderWidth、cornerRadius三个属性;

要求:这三个属性能够展现在xib中,改变属性值,能实时预览效果。

1、我们先自定义类:

 1 import UIKit
 2 
 3 // @IBDesignable:实时看到xib设置后的效果
 4 @IBDesignable
 5 class YSTextField: UITextField {
 6     
 7     // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
 8     @IBInspectable var borderColor:UIColor?{
 9         didSet{
10             self.layer.borderColor = borderColor?.cgColor
11         }
12     }
13     
14     // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
15     @IBInspectable var borderWidth:CGFloat = 0{
16         didSet{
17             self.layer.borderWidth = borderWidth
18         }
19     }
20     
21     // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
22     @IBInspectable var cornerRadius:CGFloat = 0{
23         didSet{
24             self.layer.cornerRadius = cornerRadius
25             self.layer.masksToBounds = true
26         }
27     }
28 }

2、新建一个xib,拖入一个UITextField,并把其类对应修改为我们刚自定义的类:YSTextField

3、在属性栏中我们就可以看到我们定义的属性了

原文地址:https://www.cnblogs.com/panda1024/p/6216962.html