2016-04-15 8 views
2

UIViewからUILabel制約を取得したいが、制約を得ることができない。 私はこのようなCustomView.mに制約を設定します。あなたはNSArray UIViewから制約を取得する方法プログラムによって

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

に制約を取得することができますし、インスタンスを設定することができます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

変数のように、

NSLayoutConstraint *titleLabelBottom;

してから使用し、

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

ので、あなたはクラスでtitleLabelBottomどこでも使用することができます。

が、これは制約がまだ作成されていないので、あなたはnilを取得している:)

+0

に移動すると、このビュー内にのみ配置されている制約が戻されます。例えば、 '' 'height = 0.5 * superview.height'''という制約がある場合、この配列では表示されません –

1

を助けることを願っています。

であなたの制約をロギングしてみてください。その制約をAssumming

- (void)viewDidLayoutSubviews; 

があなたのCustomViewに不可欠である、あなたはinitWithFrameメソッドの方法でその制約を作成する必要があります。

関連する問題