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

ogsagwnx  于 2022-12-24  发布在  iOS
关注(0)|答案(5)|浏览(165)

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

2w2cym1i

2w2cym1i1#

要将视图固定到屏幕底部,需要设置以下约束。
1.前导约束相对于-X的父视图
1.相对于父视图的拖尾约束-宽度
1.底部约束相对于-Y的父视图
1.高度约束附加到-高度的自身。
让我们补充一下。

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];
2admgd59

2admgd592#

由于addConstraint在将来将被弃用,因此对上一个答案进行了小扩展。以下是UI视图的扩展。请在将视图添加到层次结构后使用这些函数。

对象控制器

@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

雨燕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
    }
}
avkwfej4

avkwfej43#

此外,自iOS 9以来,它可以做超级简单的锚:

    • 雨燕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
5vf7fwbs

5vf7fwbs4#

可以按如下所示以编程方式使用自动布局约束

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

cld4siwp

cld4siwp5#

在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)
}

相关问题