Search code examples
swiftswift3autolayoutconstraints

Swift3 setting constraints relative to parent view of parent view


I have 3 classes, one is a a normal UIViewController in in which I have this code:

let CC0 = CustomUIView0()
self.addSubview(CC0)

the CustomUIView00 is a UIView class containing this code:

let CC1 = CustomUIView1()
self.addSubview(CC1)

Now for CC1 I would like to activate a constraint like this

NSLayoutConstraint.activate([

        NSLayoutConstraint(item: CC1, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: ("Parent view of CC0"), attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

])

What I tried to do is to use the UIScreen.main in the toItem place but this throws an error saying that the item needs to be an instance of UIView for this to work.

So I would essentially like to create a constraint relative to the parent of the paren view, how could I do this.

Update:

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)

])

}

This throws the problem print


Solution

  • Try below:

    // 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)
    

    EDIT: For UIView put code in awakeFromNib()

    override func awakeFromNib() {
    super.awakeFromNib()
    // Set layout constraints here
    
    }