How can I center a UIView programmatically on top of an existing UIView using Autolayout?

后端 未结 1 1309
失恋的感觉
失恋的感觉 2021-01-07 16:56

In case of a successful Foursquare checkin, my iPhone app shows adds a view on top of the view which is shown.

I want the view to be centered on the X and Y and for

相关标签:
1条回答
  • 2021-01-07 17:02

    Try this:

    NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    [superview addConstraint:xCenterConstraint];
    
    NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    [superview addConstraint:yCenterConstraint];
    

    Updated for Swift:

    NSLayoutConstraint(item: view1, attribute: .centerX, relatedBy: .equal, toItem: view2, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
    
    NSLayoutConstraint(item: view1, attribute: .centerY, relatedBy: .equal, toItem: view2, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
    
    0 讨论(0)
提交回复
热议问题