2015-10-18 100 views
0

我知道有類似的主題,但我無法弄清楚如何做簡單的事情,例如,使用自動佈局約束以編程方式設置視圖框架。它與Storyboard很容易做到,但是當我嘗試瞭解NSLayourConstraint時,我意識到我不瞭解的主題。NSLayoutConstraint以編程方式設置視圖框架

想想我們有UIView和3個按鈕。頂部的第一個按鈕有3個約束(前導和尾隨,以及頂部的視圖)。其他2個按鈕與該按鈕水平居中並具有相同的寬度。它很容易的佈局,我上傳的截圖:

enter image description here

我看了一下視覺格式的語言,但我不能明白的是 - 如何建立約束,例如,繼電器頂部(或尾隨領先)?就像下面: enter image description here

任務看起來很簡單,但儘管如此,我並沒有找到一種方法,怎麼做,編程方式與NSLayoutConstraint。你能否提供一個解決方案?謝謝。

回答

1

這裏有一個解決方案(應該去-viewDidLoad)。有幾件事值得注意:

首先,VFL不允許您創建所有可能的約束類型。特別是,需要使用+constraintWithItem:類方法在NSLayoutConstraint上進行對中。其次,如註釋中所述,您可以在水平VFL字符串中使用硬編碼的左右pad值來實現居中,但如果您需要支持不同的設備大小,則可能會導致問題。

第三,撥打-setTranslatesAutoresizingMaskIntoConstraints:是至關重要的。如果您忘記了這一點,Programmatic Autolayout將完全失效。此外,你需要確保所有的意見設置限制之前被添加到他們的superviews,否則任何約束字符串引用上海華盈會導致崩潰

NSArray *names = @[@"button1",@"button2",@"button3"]; 
NSMutableDictionary *views = [[NSMutableDictionary alloc]init]; 

for(NSUInteger i=0;i<3;i++) { 
    UIButton *b = [[UIButton alloc]init]; 
    NSString *name = names[i]; 
    [b setTitle:name forState:UIControlStateNormal]; 
    views[name] = b; 
    [b setBackgroundColor:[UIColor redColor]]; 
    [b setTranslatesAutoresizingMaskIntoConstraints:false]; 
    [self.view addSubview:b]; 
} 
//List of values to be used in the constraints 
NSDictionary *metrics = @{ 
    @"buttonWidth":@150, 
    @"bHeight":@50, //button height 
    @"topPad":@100, 
    @"vPad":@20 //vertical padding 
}; 

//Horizontal VFL string (repeated for all rows). 

for (NSString *buttonName in views.allKeys) { 
    NSString *horizontalConstraintString = [NSString stringWithFormat:@"|-(>=0)-[%@(buttonWidth)]-(>=0)-|",buttonName]; 
    NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontalConstraintString options:0 metrics:metrics views:views]; 
    [self.view addConstraints:horizontalConstraints]; 
    //Can't do centering with VFL - have to use constructor instead. You could also hardcode left and right padding in the VFL string above, but this will make it harder to deal with different screen sizes 
    NSLayoutConstraint *centerConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:views[buttonName] attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]; 

    [self.view addConstraint:centerConstraint]; 
} 

//Vertical VFL (vertical spacing of all buttons) 

NSString *verticalConstraintString = @"V:|-topPad-[button1(bHeight)]-vPad-[button2(bHeight)]-vPad-[button3(bHeight)]-(>=0)-|"; 
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:verticalConstraintString options:0 metrics:metrics views:views]; 

[self.view addConstraints:verticalConstraints]; 
[self.view layoutIfNeeded]; 
+0

謝謝豐富託利現在我明白了。你能否提供鏈接,我可以更詳細地瞭解? –