UIScrollView内的水平UIStackView不滚动

时间:2017-10-10 14:33:51

标签: ios uiscrollview autolayout xcode-storyboard uistackview

我在UIScrollView中有一个带有3个按钮的水平UIStackView。当用户更改字体大小时,我希望堆栈能够水平滚动(通过辅助功能)。

Storyboard

现在,当用户增加字体大小时,其中一个按钮会被压扁。

以下是我的约束:

UIStackView constraints

UIScrollView constraints

3 个答案:

答案 0 :(得分:1)

确保正确设置UIScrollView的内容大小。以下是一些有用的参数。

201705 201708 201706

当内容视图高于滚动视图时,滚动视图启用垂直滚动。当内容视图比滚动视图宽时,滚动视图启用水平滚动。否则,默认情况下禁用滚动。您必须动态设置内容视图大小,以便在更改字体时,内容视图比滚动视图宽度更宽。您可以将堆栈视图包装在另一个UIViewController中,并将其视为内容视图。

答案 1 :(得分:1)

似乎滚动视图和右侧按钮之间的大于或等于约束是问题所在。我将它改为Equal并且有效。

答案 2 :(得分:0)

在我这边试试,效果很好,滚动良好。

func createHorizontalStackViewWithScroll() {

 self.view.addSubview(stackScrollView)
 stackScrollView.translatesAutoresizingMaskIntoConstraints = false
 stackScrollView.heightAnchor.constraint(equalToConstant: 85).isActive = true
 stackScrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
 stackScrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
 stackScrollView.bottomAnchor.constraint(equalTo: visualEffectViews.topAnchor).isActive = true
 stackScrollView.addSubview(stackView)

 stackView.translatesAutoresizingMaskIntoConstraints = false
 stackView.topAnchor.constraint(equalTo: stackScrollView.topAnchor).isActive = true
 stackView.leadingAnchor.constraint(equalTo: stackScrollView.leadingAnchor).isActive = true
 stackView.trailingAnchor.constraint(equalTo: stackScrollView.trailingAnchor).isActive = true
 stackView.bottomAnchor.constraint(equalTo: stackScrollView.bottomAnchor).isActive = true
 stackView.heightAnchor.constraint(equalTo: stackScrollView.heightAnchor).isActive = true

 stackView.distribution = .equalSpacing
 stackView.spacing = 5
 stackView.axis = .horizontal
 stackView.alignment = .fill


 for i in 0 ..< images.count {
 let photoView = UIButton.init(frame: CGRect(x: 0, y: 0, width: 85, height: 85))
 // set button image
 photoView.translatesAutoresizingMaskIntoConstraints = false
 photoView.heightAnchor.constraint(equalToConstant: photoView.frame.height).isActive = true
 photoView.widthAnchor.constraint(equalToConstant: photoView.frame.width).isActive = true

 stackView.addArrangedSubview(photoView)
 }
 stackView.setNeedsLayout()

 }