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

我想从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 

你可以在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]]; 

所以,你可以在课堂的任何地方使用titleLabelBottom

希望这会有所帮助:)

您的结果为零,因为尚未创建约束。

尝试记录您的约束:

 - (void)viewDidLayoutSubviews; 

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