2016-04-15 56 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方法方法约束。

相关问题