我有 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 的一个实例才能工作。
所以我基本上想创建一个相对于父 View 父 View 的约束,我该怎么做。
更新:
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
}
关于Swift3 设置父 View 相对于父 View 的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720516/