我添加了UIView的子类:
class WhiteWithGreyTBBorderView: UIView {
override init (frame : CGRect) {
super.init(frame : frame)
addBehavior()
}
convenience init () {
self.init(frame:CGRectZero)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addBehavior (){
backgroundColor = UIColor.blackColor()
addTopBorderWithColor(UIColor.blackColor(), width: 5)
}
}
然后我有一个ViewExtension:
extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, self.frame.size.width, width)
self.layer.addSublayer(border)
}
func addRightBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(self.frame.size.width - width, 0, width, self.frame.size.height)
self.layer.addSublayer(border)
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, self.frame.size.height - width, self.frame.size.width, width)
self.layer.addSublayer(border)
}
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, width, self.frame.size.height)
self.layer.addSublayer(border)
}
}
我在故事板中添加了一个UIView,并将该类设置为WhiteWithGreyTBBorderView。它仍然是白色而不是黑色,在我得到的控制台中:
2015-09-03 14:28:38.802 NewsApp [6801:1954504]无法设置(borderColor)用户定义的检查属性(NewsApp.WhiteWithGreyTBBorderView):[setValue:forUndefinedKey:]:此类不是键值编码 - 兼容关键borderColor。 2015-09-03 14:28:38.803 NewsApp [6801:1954504]无法在(NewsApp.WhiteWithGreyTBBorderView)上设置(borderWidth)用户定义的检查属性:[setValue:forUndefinedKey:]:此类不符合键值编码键borderWidth。
知道什么是错的吗?
答案 0 :(得分:2)
使用Storyboard时,通过调用init(coder aDecoder: NSCoder)
创建视图。您需要做的就是在所有初始化方法addBehavior
中调用:)
这样,您可以确保在所有情况下(从代码和故事板创建视图时)正确配置视图。就是这样
您可以设置断点,并在从Storyboard或xib实例化视图时看到未调用init (frame : CGRect)
。
:)
convenience init () {
self.init(frame:CGRectZero)
addBehavior()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addBehavior()
}