我在 .Xib
文件的帮助下创建了一个自定义 View 。当我以编程方式创建 View 并将其添加到我的 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
时,它应该像我以编程方式添加时一样工作。
最佳答案
关于ios - 使用 Xib 创建的自定义 View 在 Interface Builder 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40612878/