2012-10-09 122 views
16

我已經使用以下代碼創建內viewDidLoad中一個UIView(其中「secondview」明顯是的UIView的名稱):如何以編程方式向編程創建的UIView添加約束?

secondview = [[UIView alloc] initWithFrame:self.view.frame]; 
    [secondview setBackgroundColor: [UIColor yellowColor]]; 
    secondview.translatesAutoresizingMaskIntoConstraints = NO; 
    [self.view addSubview:secondview]; 

然後內viewDidAppear我添加約束到這樣的觀點:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:secondview attribute:NSLayoutAttributeRight 
    relatedBy:NSLayoutRelationEqual 
    toItem:self.view 
    attribute:NSLayoutAttributeRight 
    multiplier:1.0f constant:-20.0f]; 
[self.view addConstraint:constraint]; 

但是,約束不適用於視圖(至少不是我能看到的)。相反,該視圖似乎從屏幕上消失。然而,如果約束代碼被註釋掉了,視圖會再次加載適當的幀(顯然沒有應用約束)。將相同的約束應用於Button或ImageView時,約束將完美應用。這導致我認爲這個問題是由於創建View時的'initWithFrame',因爲按鈕和ImageView實際上都不需要指定它的大小。

你的想法是什麼?我應該做什麼不同?

回答

12

對於任何遇到此問題的人...我需要添加多個約束。那就是訣竅。

+1

是的,這也幫助了我。顯然你需要至少兩個約束或視圖不會顯示。 – JasonD

+1

您需要儘可能多地去除歧義。這可能只有兩個,但有時會更多。 (標籤,例如要求至少兩個,它可以從文本中推斷出大小,但是你需要給它一個X和Y) – LightningStryk