如何以编程方式从UIView获取约束

时间:2016-04-15 08:01:10

标签: ios objective-c uiview autolayout nslayoutconstraint

我想从UIView获得UILabel约束,但我无法获得任何约束。 我在CustomView.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

}
ViewController.m中的

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

2 个答案:

答案 0 :(得分:2)

您可以在resolve: { modulesDirectories: [ 'node_modules' ], extensions: ['', '.json', '.js'] }, 中获得约束,

NSArray

您可以将实例变量设置为

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

然后使用,

NSLayoutConstraint *titleLabelBottom;

所以,您可以在课堂上的任何地方使用titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; [self addConstraints:@[titleLabelBottom]];

希望这会有所帮助:)

答案 1 :(得分:1)

由于尚未创建约束,因此您将获得nil。

尝试在以下位置记录约束:

- (void)viewDidLayoutSubviews;

假设该约束对于CustomView至关重要,您应该在initWithFrame方法方法中创建该约束。