我已经通过.Xib
文件创建了一个自定义视图。当我以编程方式创建视图并将其添加到我的ViewController时,它可以正常工作。但是,如果我在Interface Builder中创建一个UIView并将该类设置为CustomView
类并运行它,它将不会显示。
这是我的CustomView
类中的代码:
@IBOutlet var view: UIView!
init() {
super.init(frame:CGRect.zero)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
func setup() {
Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
view.backgroundColor = UIColor(red: 10.0/255.0, green: 30.0/255.0, blue: 52.0/255.0, alpha: 1.0)
view.translatesAutoresizingMaskIntoConstraints = false
view.isUserInteractionEnabled = true
}
func presentInView(superView:UIView) {
superView.addSubview(view)
// Define Constraints
let height = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 90.0)
view.addConstraint(height)
let topConstraint = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1.0, constant: 0.0)
let leftConstraint = NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: superView, attribute: .right, multiplier: 1.0, constant: 0.0)
superView.addConstraints([topConstraint,leftConstraint, rightConstraint])
}
在
.Xib
文件中,我将Files Owner
的类设置为CustomView
,并将IBOutlet view
连接到.Xib
的主视图。在我的ViewController中,我这样做是为了向其中添加
CustomView
:let customView = CustomView()
customView.presentInView(superView: self.view)
当我在Interface Builder中添加
UIView
时,它应该像我以编程方式进行操作时一样工作。 最佳答案