0

I have two subviews that I created, one in Storyboard one with code, I want to anchor the second view (created with code) to the first view (in storyboard) with some constraints so that the second view sits below the first view:

class ViewController: UIViewController{
    @IBOutlet weak var view1: UIView!
    override func viewDidLoad(){
        super.viewDidLoad()
        setUp()
    }

    func setUp(){

        var view2 = UIView()
        view2.setTranslatesAutoresizingMaskIntoConstraints(false)
        view2.frame = CGRectMake(10,10,10,10)

        self.view.addSubview(view2)
        self.view.addConstraint(NSLayoutConstraint(item: view1, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: view2, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
    }
}

The problem is that I got an error saying When added to a view, the constraint's items must be descendants of that view. Is it bad practice to have some views in storyboard and others in code?

1 Answer 1

1

You have a few problems.

First, the error means that view1 and view2 are not both part of self.view's view hierarchy. This is probably because view1 hasn't been decoded from the storyboard yet. Try moving this code from viewDidLoad() to awakeFromNib(), which is when they're guaranteed to have been loaded.

Second, you're trying to set the view's frame:

view2.frame = CGRectMake(10,10,10,10)

This frame will get overwritten by the layout engine making it pointless. Delete this line.

If you're going to use auto-layout, you need to unambiguously specify both the size (height & width) and position (x & y) of the view. The constraint you added only specifies the y-origin, so you also need to add more constraints (probably 3 more) to specify the x-origin, the width, and the height, which are currently undefined.


Is it bad practice to have some views in storyboard and others in code?

No, it's common.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! Just one more question: Originally I had view2.frame = CGRectMake(self.view1.frame.origin.x, self.view1.frame.origin.y + self.view1.frame.height + 10, self.view1.frame.width, self.view.frame.height * 0.3), however, this doesn't put view2 where I wanted without constraints and my question is why doesn't it put it at the location I specified with (x,y,width, height) -- if I have to use constraints to specify the location then (x,y) in CGRectMake seems a little redundant to me.
@user245954 You should delete that entire line. The entire point of auto layout is that you don't set frames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.