我正在尝试为UIScrollView添加标签。我正在添加一个顶部约束和一个前导约束。 标签没有出现。
这是我的代码。
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
self.label.translatesAutoresizingMaskIntoConstraints = NO;
self.label.backgroundColor = [UIColor clearColor];
self.label.textAlignment = NSTextAlignmentCenter;
self.label.textColor=[UIColor whiteColor];
self.label.text = @"Hello";
[self.imageCarouselScrollView addSubview:self.label];
[self bringSubviewToFront:self.label];
self.titleLabelTopConstraint = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.imageCarouselScrollView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:20];
NSLayoutConstraint *titleLeadingConstraint = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.imageCarouselScrollView
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:20];
[self addConstraints:@[self.titleLabelTopConstraint,titleLeadingConstraint]];
答案 0 :(得分:0)
您必须在滚动视图的右侧(水平滚动)或底部(垂直滚动)中包含约束,以便它可以推断出内容大小。
答案 1 :(得分:0)
我尝试评论你的代码:
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; //if 'translatesAutoresizingMaskIntoConstraints=NO' frame not work work anymore. Use CGRectZero instead
self.label.translatesAutoresizingMaskIntoConstraints = NO;
self.label.backgroundColor = [UIColor clearColor];
self.label.textAlignment = NSTextAlignmentCenter;
self.label.textColor=[UIColor whiteColor];
self.label.text = @"Hello";
[self.imageCarouselScrollView addSubview:self.label]; //Your self.label added on 'self.imageCarouselScrollView' but your constraints added on self
[self bringSubviewToFront:self.label]; // ??? Why?
self.titleLabelTopConstraint = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.imageCarouselScrollView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:20]; //it constrain means: "self view top edge equal to self.imageCarouselScrollView bottom + offset 20 "
NSLayoutConstraint *titleLeadingConstraint = [NSLayoutConstraint
constraintWithItem:self
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.imageCarouselScrollView
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:20];//it constrain means: "self view Leading edge equal to self.imageCarouselScrollView Trailing + offset 20 "
[self addConstraints:@[self.titleLabelTopConstraint,titleLeadingConstraint]];
现在我几乎没有问题: