如何以编程方式创建布局约束

时间:2015-07-27 10:43:37

标签: ios iphone constraints

我在通用应用程序的底部显示一个视图,并在我的视图中动态添加此视图。我希望每次都像iAd一样在底部显示这个视图。在两个方向。如何为此添加约束。请建议。

谢谢

5 个答案:

答案 0 :(得分:98)

要将视图固定到屏幕底部,您需要设置以下约束。

    关于 - X 的父视图
  1. 领先约束 关于父视图的
  2. 尾随约束 - 宽度
  3. 底部约束,与父视图相关 - Y
  4. 高度限制附加到自身 - 高度
  5. 让我们添加。

    UIView *subView=bottomView;
    UIView *parent=self.view;
    
    subView.translatesAutoresizingMaskIntoConstraints = NO;
    
    //Trailing    
    NSLayoutConstraint *trailing =[NSLayoutConstraint
                                    constraintWithItem:subView
                                    attribute:NSLayoutAttributeTrailing
                                    relatedBy:NSLayoutRelationEqual
                                    toItem:parent   
                                    attribute:NSLayoutAttributeTrailing
                                    multiplier:1.0f
                                    constant:0.f];
    
    //Leading
    
    NSLayoutConstraint *leading = [NSLayoutConstraint
                                       constraintWithItem:subView
                                       attribute:NSLayoutAttributeLeading
                                       relatedBy:NSLayoutRelationEqual
                                       toItem:parent
                                       attribute:NSLayoutAttributeLeading
                                       multiplier:1.0f
                                       constant:0.f];
    
    //Bottom
    NSLayoutConstraint *bottom =[NSLayoutConstraint
                                     constraintWithItem:subView
                                     attribute:NSLayoutAttributeBottom
                                     relatedBy:NSLayoutRelationEqual
                                     toItem:parent
                                     attribute:NSLayoutAttributeBottom
                                     multiplier:1.0f
                                     constant:0.f];
    
    //Height to be fixed for SubView same as AdHeight
    NSLayoutConstraint *height = [NSLayoutConstraint
                                   constraintWithItem:subView
                                   attribute:NSLayoutAttributeHeight
                                   relatedBy:NSLayoutRelationEqual
                                   toItem:nil
                                   attribute:NSLayoutAttributeNotAnAttribute
                                   multiplier:0
                                   constant:ADHeight];
    
        //Add constraints to the Parent
        [parent addConstraint:trailing];
        [parent addConstraint:bottom];
        [parent addConstraint:leading];
    
        //Add height constraint to the subview, as subview owns it.
        [subView addConstraint:height];
    

    希望这有帮助。

    干杯。

答案 1 :(得分:11)

以前回答的小扩展名,因为将来会弃用addConstraint。这是UI视图的扩展。将视图添加到层​​次结构后,请使用这些功能。

<强> OBJC

@implementation UIView (Constraints)

-(void)addConstaintsToSuperviewWithLeftOffset:(CGFloat)leftOffset topOffset:(CGFloat)topOffset {

    self.translatesAutoresizingMaskIntoConstraints = false;

    [[NSLayoutConstraint constraintWithItem: self
                                  attribute: NSLayoutAttributeLeading
                                  relatedBy: NSLayoutRelationEqual
                                     toItem: self.superview
                                  attribute: NSLayoutAttributeLeading
                                 multiplier: 1
                                   constant: leftOffset] setActive:true];

    [[NSLayoutConstraint constraintWithItem: self
                                  attribute: NSLayoutAttributeTop
                                  relatedBy: NSLayoutRelationEqual
                                     toItem: self.superview
                                  attribute: NSLayoutAttributeTop
                                 multiplier: 1
                                   constant: topOffset] setActive:true];
}

-(void)addConstaintsWithWidth:(CGFloat)width height:(CGFloat)height {

    self.translatesAutoresizingMaskIntoConstraints = false;


    [[NSLayoutConstraint constraintWithItem: self
                                  attribute: NSLayoutAttributeWidth
                                  relatedBy: NSLayoutRelationEqual
                                     toItem: nil
                                  attribute: NSLayoutAttributeNotAnAttribute
                                 multiplier: 1
                                   constant: width] setActive:true];

    [[NSLayoutConstraint constraintWithItem: self
                                  attribute: NSLayoutAttributeHeight
                                  relatedBy: NSLayoutRelationEqual
                                     toItem: nil
                                  attribute: NSLayoutAttributeNotAnAttribute
                                 multiplier: 1
                                   constant: height] setActive:true];
}

@end

Swift 3

extension UIView {

    public func addConstaintsToSuperview(leftOffset: CGFloat, topOffset: CGFloat) {

        self.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint(item: self,
                           attribute: .leading,
                           relatedBy: .equal,
                           toItem: self.superview,
                           attribute: .leading,
                           multiplier: 1,
                           constant: leftOffset).isActive = true

        NSLayoutConstraint(item: self,
                           attribute: .top,
                           relatedBy: .equal,
                           toItem: self.superview,
                           attribute: .top,
                           multiplier: 1,
                           constant: topOffset).isActive = true
    }

    public func addConstaints(height: CGFloat, width: CGFloat) {

        self.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint(item: self,
                           attribute: .height,
                           relatedBy: .equal,
                           toItem: nil,
                           attribute: .notAnAttribute,
                           multiplier: 1,
                           constant: height).isActive = true


        NSLayoutConstraint(item: self,
                           attribute: .width,
                           relatedBy: .equal,
                           toItem: nil,
                           attribute: .notAnAttribute,
                           multiplier: 1,
                           constant: width).isActive = true
    }
}

答案 2 :(得分:10)

同样从iOS 9开始,它可以通过锚点完成:

Swift 3

extension UIView {

    func addConstaintsToSuperview(leadingOffset: CGFloat, topOffset: CGFloat) {

        guard superview != nil else {
            return
        }

        translatesAutoresizingMaskIntoConstraints = false

        leadingAnchor.constraint(equalTo: superview!.leadingAnchor,
                                 constant: leadingOffset).isActive = true

        topAnchor.constraint(equalTo: superview!.topAnchor,
                             constant: topOffset).isActive = true
    }

    func addConstaints(height: CGFloat, width: CGFloat) {

        heightAnchor.constraint(equalToConstant: height).isActive = true
        widthAnchor.constraint(equalToConstant: width).isActive = true
    }

}

OBJC 类别

@implementation UIView (Constraints)

-(void)addConstaintsToSuperviewWithLeadingOffset:(CGFloat)leadingOffset topOffset:(CGFloat)topOffset
{
    if (self.superview == nil) {
        return;
    }

    self.translatesAutoresizingMaskIntoConstraints = false;

    [[self.leadingAnchor constraintEqualToAnchor:self.superview.leadingAnchor
                                        constant:leadingOffset] setActive:true];

    [[self.topAnchor constraintEqualToAnchor:self.superview.topAnchor
                                   constant:topOffset] setActive:true];
}

-(void)addConstaintsWithHeight:(CGFloat)height width:(CGFloat)width
{
    [[self.heightAnchor constraintEqualToConstant:height] setActive:true];
    [[self.widthAnchor constraintEqualToConstant:width] setActive:true];
}

@end

答案 3 :(得分:2)

您可以像下面这样以编程方式使用自动布局约束

fileprivate func setupName(){
        let height = CGFloat(50)

        lblName.text = "Hello world"
        lblName.backgroundColor = .lightGray

        //Step 1
        lblName.translatesAutoresizingMaskIntoConstraints = false

        //Step 2
        self.view.addSubview(lblName)

        //Step 3
        NSLayoutConstraint.activate([

            lblName.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
            lblName.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
            lblName.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor,constant: -height),
            lblName.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
            ])

    }

Output screenshot

答案 4 :(得分:0)

在Swift 4中扩展@Alex Shubin解决方案,我执行以下操作:

有时,我需要添加可变数量的约束,在本例中为3,因为高度将在后面计算。

keyboard.addConstaints(top: nil, right: 0.0, bottom: 0.0, left: 0.0, width: nil, height: nil)

您必须小心添加所有必需的内容,并确保没有任何冲突的约束。

extension UIView {
    func addConstaints(top: CGFloat?, right: CGFloat?, bottom: CGFloat?, left: CGFloat?, width: CGFloat?, height: CGFloat?) {
        translatesAutoresizingMaskIntoConstraints = false
        if top != nil { self.addConstaint(top: top!) }
        if right != nil { self.addConstaint(right: right!) }
        // Add lines for bottom, left, width an heigh
        // ...
    }
    func addConstaint(top offset: CGFloat) {
        guard superview != nil else { return }
        topAnchor.constraint(equalTo: superview!.topAnchor, constant: offset).isActive = true
    }
}

要验证所有视图是否布局正确,您可以检查superView的.constraints属性,或者可以检查框架:

override func viewDidLayoutSubviews() {
    print(keyboard.frame)
}