我有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)
])
}
这会引发问题打印
答案 0 :(得分:1)
尝试以下:
// 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
}