在UIScrollView中约束UIStackView排列视图的宽度

时间:2016-02-08 16:33:06

标签: ios objective-c uiscrollview uistackview

我在UIScrollView中嵌入了一个UIStackView。当我将视图作为排列的子视图添加到UIStackView时,它的宽度会扩展到框架之外并导致出现水平滚动条,即使我添加了水平宽度布局约束。 我不希望UIScrollView水平扩展

viewDidLoad中以编程方式在UIScrollView中创建UIStackView的代码:

_scrollView = [UIScrollView new];
_scrollView.delegate = self;
_scrollView.translatesAutoresizingMaskIntoConstraints = NO;
_scrollView.pagingEnabled = YES;
[self.view addSubview:_scrollView];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:@{@"scrollView": _scrollView}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:@{@"scrollView": _scrollView}]];

// configure stackView
_stackView = [UIStackView new];
_stackView.translatesAutoresizingMaskIntoConstraints = NO;
_stackView.axis = UILayoutConstraintAxisVertical;
[_scrollView addSubview:_stackView];
[_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[stackView]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:@{@"stackView": _stackView}]];
[_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[stackView]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:@{@"stackView": _stackView}]];

然后我添加自定义视图和AutoLayout约束以将子视图的宽度限制为stackView&#39>:

CustomView *customView = [CustomView loadFromXib]; // helper to load from xib
[_stackView addArrangedSubview:customView];
[_stackView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[customView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:@{@"customView": customView}]];

但是,生成的CustomView大约是帧宽度的两倍。 CustomView中的IB集合约束都没有固定的宽度,因此我希望内容可以调整大小以适应框架。我做错了什么?

0 个答案:

没有答案