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

标签 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

最佳答案

您可以在 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

希望这会有所帮助:)

关于ios - 如何以编程方式从 UIView 获取约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641487/

相关文章:

ios - OpenGL 纹理在使用 Swift 的 iOS 上不显示

ios - 解析查询未按降序加载

ios - 模拟器无法启动,在将我的 Xcode 更新到 8.2.1 后卡在验证 "Simulator"

iphone - 当我把自己放进去时,NSArray 失去了值(value)

iphone - iOS:让 NSAttributedString-Additions-for-HTML 工作?

objective-c - iOS/Objective-C : transitionWithView custom animation block resizes view immediately, 未超过持续时间

ios - 用 CAShapeLayer 实现绘制渐变圆弧

ios - Swift: View Controller 内的 tableView 始终为 "found nil while unwr..."

ios - 带有互联网连接案例的 XCTestCase

swift - UITapGestureRecognizer 响应不正确的 UIView