gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:32:46 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com