Подтвердить что ты не робот

Как программно создавать ограничения компоновки

Я показываю представление в нижней части универсального приложения и динамически добавляю его в мое представление. Я хочу показывать это представление снизу каждый раз, как iAd. в обеих ориентациях. Как я могу добавить ограничения для этого. Пожалуйста, предложите.

Спасибо

4b9b3361

Ответ 1

Чтобы зафиксировать представление в нижней части экрана, вам нужно установить следующие ограничения.

  • Ведущее ограничение по отношению к Parent View для - X
  • Trailing Constraint в отношении родительского представления для - Ширина
  • Нижнее ограничение относительно родительского представления для - Y
  • Ограничение высоты прикреплено к self для - Высота.

Давайте добавим.

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

Надеюсь, что это поможет.

Приветствия.

Ответ 2

Небольшое расширение для предыдущего ответа, потому что addConstraint будет устаревать в будущем. Вот расширение для просмотра пользовательского интерфейса. Используйте эти функции после добавления представления в иерархию.

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

Ответ 3

Также, поскольку 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