Swift 怎么用xib 自定义View
2016-04-14 · 百度知道合伙人官方认证企业
swift用xib自定义View的方法如下:
1. 创建一个IDView,添加一个IDView.Xib
2. 对IDCard.xib添加约束
3、在IDCard.xib的 File's Owner class 设置为IDCard:
4、在IDCard.swift中添加如下代码,把xib的view连线到代码上的contentView:
5、绑定xib,实现 @IBInspectable, @IBDesignable这几部分代码
@IBDesignable
class IDCard: UIView {
@IBOutlet var contentView: UIView!
@IBInspectable
var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable
var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable
var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initialFromXib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialFromXib()
}
func initialFromXib() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "IDCard", bundle: bundle)
contentView = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
contentView.frame = bounds
addSubview(contentView)
}
}
6、运行代码,结果如下