Swift3 设置父 View 相对于父 View 的约束

标签 swift swift3 autolayout constraints

我有 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/

相关文章:

ios - 如何在 SWIFT 中从 SKSpriteNode 创建 CGPath

ios - 在 Swift 3 中将数据保存到 .plist 文件

ios - 自动布局横向和纵向模式的不同约束

ios - 选择时调整单元格大小时出现 NSAutoResizingMaskLayoutConstraint 错误

ios - 为什么我的 Google map 应用程序不打印出点击的坐标?

swift - 单元格中的图像未出现在搜索结果中

json - NSCoding 和 Codable 属性 <=> JSON 格式 <=>(读/写)文件

ios - reloadData 不调用 cellForItemAt

core-data - Swift 3 中的新核心数据

ios - 可变长度标签、tableview 行高和自动布局