我正在以编程方式构建一个视图,并使用自动布局,完全不使用界面生成器。在自定义的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像素的偏移量以显示它在哪里。) 那么为什么滚动视图的右边实际上是左边?如何正确地对齐到屏幕的右侧?我错在哪里了?这让我疯狂!
谢谢任何帮助!
最终布局图像:
我希望最终布局看起来像这样:
如果旋转到横屏,我期望它看起来像这样: