【发布时间】:2023-03-18 18:05:01
【问题描述】:
我在.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 时,它应该像我以编程方式执行它时一样工作。
【问题讨论】:
标签: ios swift xcode uiview interface-builder