我正试图将nib文件加载到collectionViewController内部的视图中,作为视差标头,但加载视图后,视图的宽度为0.0,因此无法显示。如果我加载任何其他视图,宽度是可以的,但加载后这个视图的宽度变为零。这是我的代码。
class CastHeader: UIView{
private func commonInit() {
guard let view = Bundle.main.loadNibNamed("CastHeader", owner: self, options: nil)![0] as? UIView else{return}
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let bindings = ["view": view]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options:[], metrics:nil, views: bindings))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options:[], metrics:nil, views: bindings))
}
// MARK: User interface
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
awakeFromNib()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
awakeFromNib()
}
}
有什么想法吗?提前感谢
从init方法中删除commongInit()
//在CastHeader
类中添加以下方法
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
commonInit()
}
请尝试此解决方案。这可能会对你有所帮助。