简体   繁体   中英

How to add constraints programmatically to a programmatically created UIView?

I have created a UIView using the following code within viewDidLoad (where 'secondview' obviously is the name of the UIView):

secondview = [[UIView alloc] initWithFrame:self.view.frame];
    [secondview setBackgroundColor: [UIColor yellowColor]];
    secondview.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:secondview];

Then within viewDidAppear I added constraints to this view:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:secondview attribute:NSLayoutAttributeRight
    relatedBy:NSLayoutRelationEqual
    toItem:self.view
    attribute:NSLayoutAttributeRight
    multiplier:1.0f constant:-20.0f];
[self.view addConstraint:constraint];

However, the constraints are not applied to the view (atleast not that I can see). Instead, the view simply seems to disappear from the screen. If the constraint code is commented out however, the view once again loads with the appropriate frame (obviously without the constraints being applied). When applying the same constraints to a Button or ImageView, the constraints are applied perfectly. This has lead me to think that the issue is because of 'initWithFrame' when creating the View, as neither the button nor ImageView actually require it's size to be specified.

What are your thoughts? What should I do differently?

For anyone who comes across this... I needed to add more than one constraint. That did the trick.

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