2015-07-27 4 views
39

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

Благодаря

+0

Хочет увеличить высоту Просмотр по устройству? – iphonic

+0

№ Высота исправления такая же, как у iAd. –

+0

Убедитесь, что вы видите [On iOS, каковы различия между полями, кросс-вставками, вставками содержимого, прямоугольниками выравнивания, краями макета, привязками) (https://stackoverflow.com/questions/37796884/on-ios-what-are -The-различие между ними, наценками краем-вставками-контентом-вставками-а/47614397 # 47614397). Это улучшит ваше понимание полей, якорей, макетов ... – Honey

ответ

75

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

  1. Leading Constraint с относительно родительского вида для - X
  2. Продольный Constraint с относительно родительского вида для - Ширина
  3. Bottom Constraint с относительно родительского вида для - Y
  4. H восемь Constraint прилагается к себе для - Высота.

Добавляет.

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

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

Cheers.

+0

Значение 'attribute' на' * height' должно фактически быть 'NSLayoutAttributeNotAnAttribute', а не' 0'. – chicobermuda

+0

@dperk NSLayoutAttributeNotAnAttribute = 0: NSLayoutAttribute - это значения перечисления, где он определен как 0, поэтому оба они не имеют разницы в выборе того, что вы хотите использовать. – iphonic

+3

Правда, хотя лучше всего поддерживать соответствие имен перечислений. Для 0 я уступаю; это не большое дело. Но всегда лучше быть последовательным. – chicobermuda

6

Маленькое расширение для предыдущего ответа, потому что 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 
    } 
} 
+0

https://stackoverflow.com/questions/45454992 –

3

Также с прошивкой 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 
-2

это лучше один по сравнению с описанным выше способом becoz количества линий или менее

0

Расширение решения @Alex Шубин в Swift 4, я следующее:

Иногда мне нужно добавить переменное количество ограничений, в этом случае 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 
    } 
} 

Чтобы убедиться, что все взгляды были непринужденными правильно, вы можете проверить .constraints свойства SuperView или вы можете проверить кадр в:

override func viewDidLayoutSubviews() { 
    print(keyboard.frame) 
} 
Смежные вопросы