ios - 使用 Xib 创建的自定义 View 在 Interface Builder 中不起作用

标签 ios swift xcode uiview interface-builder

我在 .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 时,它应该像我以编程方式添加时一样工作。

最佳答案

你在Interface Builder中给你的uiview分配了CustomView Class吗。

Assigning UIView As you CustomView

关于ios - 使用 Xib 创建的自定义 View 在 Interface Builder 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40612878/

相关文章:

swift - Realm :创建新角色并向其添加用户失败

swift - 错误: Value of type 'CGRect' has no member 'center'

ios - 来自 Swift 3 中路径或文件名的 UIImage

ios - 如何删除 Xcode 6 中的 "Run Script"构建阶段?

ios - 为什么我的本地通知没有出现在我的实际设备上? (iPhone 5C)

ios - 在 ASTableNode 中的 ASCellNode 之间和周围添加间距的最佳方法?

ios - 类中的 extern NSString *const。

ios - Realm, Swift, 多对多关系

xcode - 如何在 Xcode 上打开 .pbproj?

iphone - 为什么设备和模拟器的构建不同?