2016-02-05 45 views
0

我試圖以編程方式設置UIButton垂直和水平使用AutoLayouts中心這裏需要援助中心設置的UIButton是我的代碼:使用自動版式

- (void)awakeFromNib { 
UIView *av = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 35.0)]; 

UIButton *doneButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 37, 30)]; 

//UIButton title, color, backgroung color, targer action ... 

NSLayoutConstraint* cn3 = [NSLayoutConstraint constraintWithItem:doneButton 
                  attribute:NSLayoutAttributeCenterX 
                  relatedBy:NSLayoutRelationEqual 
                  toItem:av 
                  attribute:NSLayoutAttributeCenterX 
                 multiplier:1.0 
                  constant:0]; 
    [av addConstraint:cn3]; 

    NSLayoutConstraint* cn4 = [NSLayoutConstraint constraintWithItem:doneButton 
             attribute:NSLayoutAttributeCenterY 
             relatedBy:NSLayoutRelationEqual 
             toItem:av 
             attribute:NSLayoutAttributeCenterY 
            multiplier:1.0 
             constant:0]; 
    [av addConstraint:cn4]; 

[av addSubview:doneButton]; 
    self.theTextField.inputAccessoryView = av; 
} 

上面的代碼中,除了一件事做工精細,我越來越控制檯這樣的警告:

視圖層次不用於約束準備: NSLayoutConstraint:0x7fcfc494efb0 的UIButton:0x7fcfc2624420'Done'.centerX == UIView:0x7fcfc2624230.centerX

當添加到視圖中時,約束條目必須是該視圖的後代 (或視圖本身)。如果在組裝視圖層次之前需要解析約束 ,這將會崩潰。打破 - [UIView(UIConstraintBasedLayout)_viewHierarchyUnpreparedForConstraint:]進行調試。

並得到同樣的警告爲Y.

請告訴我什麼錯誤爲什麼我收到這樣的警告?

回答

2

doneButton添加到av視圖之前設置您的約束。

[av addSubview:doneButton]; 

[av addConstraint:cn3]; 
[av addConstraint:cn4]; 
+0

Perfecto :)非常感謝你..... –

相關問題