我有 3 个类,一个是普通的 UIViewController,其中有以下代码:
let CC0 = CustomUIView0()
self.addSubview(CC0)
CustomUIView00是一个包含以下代码的UIView类:
let CC1 = CustomUIView1()
self.addSubview(CC1)
现在对于 CC1,我想激活这样的约束
NSLayoutConstraint.activate([
NSLayoutConstraint(item: CC1, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: ("Parent view of CC0"), attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
])
我试图做的是在 toItem 地方使用 UIScreen.main ,但这会引发错误,指出该项目需要是 UIView 的实例才能工作。
因此,我本质上想相对于paren视图的父级创建一个约束,我该怎么做。
更新:
UIViewController:
let CC0 = UICustomUIView0()
self.view.insertSubview(self.CC0, at: 0)
UICustomUIView0:
init {
super.init(frame: UIScreen.main.bounds);
let CC1 = UICustomUIView1()
guard let CC1Parent = self.CC1.superview, let CC0Parent = CC1Parent.superview else {
print("Problem")
return
}
self.view.addSubview(CC1)
NSLayoutConstraint.activate([
NSLayoutConstraint(item: CC1, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: CC0Parent, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
])
}
这会引发问题打印
试试下面:
// guard below ensures you have the parent AND grandparent views
guard let cc1Parent = cc1.superview, let cc0Parent = cc1Parent.superview else {
// problem with accessing parent views
return
}
// now just set your constraints as per below
NSLayoutConstraint(item: cc1, attribute: .top, relatedBy: .equal, toItem: cc1Parent, attribute: .top, multiplier: 1, constant: 0)
编辑:对于 UIView 把代码放在awakeFromNib()
override func awakeFromNib() {
super.awakeFromNib()
// Set layout constraints here
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句