2014-07-09 131 views
5

有沒有什麼方法可以用NSLayoutConstraints設置UIView的寬度和高度? 例如我有以下限制設置視覺格式化語言,按鈕寬度和高度約束

subView.setTranslatesAutoresizingMaskIntoConstraints(false); 
     let cons:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("[subView(99)]", options:nil, metrics: nil, views: ["subView":subView]); 
     self.view.addConstraints(cons); 

這臺僅寬,怎麼還添加了一個高度?

回答

11

兩個可能的選擇:

[view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
NSArray* vConstraints = [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view(25)]|" options:0 metrics:nil views:view]]; 
[parentView addConstraints:vConstraints]; 

NSLayoutConstraint* vConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:25]; 
[parentView addConstraint:vConstraint]; 
5

對於垂直佈局,只需添加五:到VFL字符串的開頭:

subView.setTranslatesAutoresizingMaskIntoConstraints(false); 

    let horizontalCons:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("[subView(99)]", options:nil, metrics: nil, views: ["subView":subView]); 
    let veritcleCons:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:[subView(50)]", options:nil, metrics: nil, views: ["subView":subView]); 

    self.view.addConstraints(horizontalCons); 
    self.view.addConstraints(veritcleCons);