2016-04-15 55 views
2

我想從UIView獲取UILabel約束,但我無法獲得任何約束。 我設置的約束在CustomView.m這樣的:如何以編程方式從UIView獲取約束

在ViewController.m
- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     _titleLabel = [UILabel new]; 
     [self addSubview:_titleLabel]; 
    } 
    return self; 
} 

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    _titleLabel.translatesAutoresizingMaskIntoConstraints = NO; 
    NSLayoutConstraint *titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel 
               attribute:NSLayoutAttributeBottom 
               relatedBy:NSLayoutRelationEqual 
               toItem:self 
               attribute:NSLayoutAttributeCenterY 
              multiplier:1 
               constant:0]; 
    [self addConstraints:@[titleLabelBottom]]; 

    ...more code 

} 

CustomView *view = [CustomView alloc] initWithFrame:viewFrame]; 
NSLog(@"%@",view.titleLabel.constraints); // nil 
+1

'layoutSubviews:'被調用很多次,並且您總是創建一個新的約束。將約束創建移動到您的初始化程序 – tgyhlsb

回答

2

您可以在NSArray一樣得到約束,

NSArray *constraintArr = self.backButton.constraints; 
NSLog(@"cons : %@",constraintArr); 

,你可以設置實例變量like,

NSLayoutConstraint *titleLabelBottom;

再使用,

titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel 
              attribute:NSLayoutAttributeBottom 
              relatedBy:NSLayoutRelationEqual 
              toItem:self 
              attribute:NSLayoutAttributeCenterY 
             multiplier:1 
              constant:0]; 
[self addConstraints:@[titleLabelBottom]]; 

所以,你可以在課堂上使用titleLabelBottom任何地方。

希望這將有助於:)

+0

它僅返回放置在此視圖內的約束。例如,如果你的約束'''height = 0.5 * superview.height''' - 你不會在這個數組中看到它 –

1

因爲限制還沒有被創建你越來越爲零。

嘗試登入您的約束:

- (void)viewDidLayoutSubviews; 

Assumming這個約束是必不可少的你CustomView,你應該建立在你的initWithFrame方法方法約束。

相關問題