简体   繁体   中英

Add constraints between two sub views programmatically in Swift

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM