Ich möchte UILabel Einschränkungen von UIView bekommen, aber ich kann keine Einschränkungen erhalten. stelle ich die Einschränkungen in CustomView.m wie folgt aus:Wie bekomme ich Constraints von UIView Programmatisch
- (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
}
in ViewController.m
CustomView *view = [CustomView alloc] initWithFrame:viewFrame];
NSLog(@"%@",view.titleLabel.constraints); // nil
'layoutSubviews:' wird oft aufgerufen, und Sie erstellen immer eine neue Einschränkung. Verschieben Sie die Constraint-Erstellung in Ihren Initialisierer. – tgyhlsb