<分区>
在我当前的项目中,我经常创建一个 UIView 以在 View 上放置一个灰色矩形。我通常先在布局上放置白色 View ,然后在 viewDidLoad()
中设置所有边框。现在我决定通过编写一个自动设置 View 边框的子类来加快速度,然后将所有这些 View 设置为使用该子类。但是我不知道把这段代码放在子类的什么地方:
self.layer.borderWidth = 2;
self.layer.borderColor = UIColor.grayColor().CGColor;
我是否将它放在 override init()
上?我是否需要为 UIView 覆盖每个版本的 init
?或者有更好的方法吗?
谢谢。
PS:如果还有什么方法可以让边框在 Storyboard设计时立即显示(我认为它与 drawable
有关但我完全不明白它),我将不胜感激!
编辑:
从接受的答案中,我得到了这个答案:https://stackoverflow.com/a/33721647/3003927基本上是这样的:
import UIKit
class MyView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
didLoad()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didLoad()
}
convenience init() {
self.init(frame: CGRectZero)
}
func didLoad() {
//Place your initialization code here
self.layer.borderWidth = 2;
self.layer.borderColor = UIColor.grayColor().CGColor;
}
}