这个问题在这里已有答案:
在我当前的项目中,我经常创建一个UIView来在视图上放置一个灰色矩形 . 我通常首先在布局上放置白色视图,然后在 viewDidLoad()
中设置所有边框 . 现在我决定通过编写一个自动设置视图边框的子类来加快速度,然后将所有这些视图设置为使用该子类 . 但我不知道将此代码放在子类的哪个位置:
self.layer.borderWidth = 2;
self.layer.borderColor = UIColor.grayColor().CGColor;
我把它放在 override init()
上吗?我是否需要为UIView覆盖 init
的每个版本?或者有更好的方法吗?
谢谢 .
PS:如果还有任何方法可以立即在故事板设计时间显示边框(我认为它与 drawable
有关,但我不会非常感激!
EDIT:
从接受的答案,我得到这个答案: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;
}
}
2 回答
这里有一个非常详细的答案:
Proper practice for subclassing UIView?
基本上,你应该覆盖:
init?(coder aDecoder: NSCoder)
和init(frame: CGRect)
以及awakeFromNib()
. 只需从你设置边框的地方调用另一个函数 .您需要创建UIView的子类,并根据您在此类中的需要声明IBInspectable属性 .
尝试以下链接作为示例:
http://nshipster.com/ibinspectable-ibdesignable/
https://www.captechconsulting.com/blogs/ibdesignables-in-xcode-6-and-ios-8