簡體   English   中英

如何以編程方式將約束添加到以編程方式創建的UIView?

[英]How to add constraints programmatically to a programmatically created UIView?

我在viewDidLoad中使用以下代碼創建了一個UIView(其中'secondview'顯然是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實際上都不需要指定它的大小。

你怎么看? 我該怎么辦?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM