【问题标题】:How to get constraints from UIView Programmatically如何以编程方式从 UIView 获取约束
【发布时间】:2016-08-07 02:13:12
【问题描述】:

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

【问题讨论】:

  • layoutSubviews: 被多次调用,你总是创建一个新的约束。将约束创建移动到您的初始化程序

标签: ios objective-c uiview autolayout nslayoutconstraint


【解决方案1】:

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

希望这会有所帮助:)

【讨论】:

  • 它只返回放置在这个视图中的约束。例如,如果你有约束 height = 0.5*superview.height - 你不会在这个数组中看到它
【解决方案2】:

您将得到 nil,因为尚未创建约束。

尝试将您的约束记录在:

- (void)viewDidLayoutSubviews;

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

【讨论】:

    猜你喜欢
    • 2015-06-03
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多