【发布时间】:2014-03-04 04:23:53
【问题描述】:
我正在以编程方式构建视图并使用自动布局,根本没有界面构建器。在自定义 ScrollView 控制器中,我添加了一个 UILabel 和一个 UIButton 作为子视图。我想将标签对齐到屏幕左侧,将按钮对齐到屏幕右侧。出于某种原因,我的按钮仅与滚动视图的左侧对齐。我已经缩减了我的代码,所以它只有这两个标签,我不明白为什么它不会与右边对齐。
HWScrollViewController.m(我如何初始化主滚动视图)
- (void)loadView
{
self.scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.scrollView.delegate = self;
self.view = self.scrollView;
}
HWListingDetailViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *priceLabel = [[UILabel alloc] init];
UIButton *favouriteButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[priceLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[favouriteButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[priceLabel setText:@"$125.00"];
[favouriteButton setTitle:@"Add to Favourites" forState:UIControlStateNormal];
[self.view addSubview:priceLabel];
[self.view addSubview:favouriteButton];
[self.view addConstraints:@[
[NSLayoutConstraint constraintWithItem:priceLabel
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0],
[NSLayoutConstraint constraintWithItem:priceLabel
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:5],
[NSLayoutConstraint constraintWithItem:favouriteButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0],
[NSLayoutConstraint constraintWithItem:favouriteButton
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1
constant:5],
}
如您所见,绿色价格标签对齐正确,但红色按钮远离屏幕左侧。 (我给了它 5 个像素的偏移量来显示它的位置。)那么,为什么滚动视图的右侧实际上是左侧?如何正确对齐屏幕右侧?我哪里做错了?这快把我逼疯了!
感谢您的帮助!
最终布局图片: 我希望最终的布局是这样的:
如果旋转到横向,我希望它看起来像这样:
【问题讨论】:
标签: ios ios7 uiscrollview autolayout nslayoutconstraint