以编程方式创建的ScrollView无法正常工作

时间:2019-08-12 08:53:15

标签: swift

我仍然不了解UIScrollView的窍门... 我想创建一个将其添加到容器并向其中添加StackView:

let scroll = UIScrollView()
scroll.contentSize = CGSize(width: stackWidth, height: stackHeight)
bottomContainer.addSubview(scroll)
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .equalSpacing
scroll.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
scroll.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    scroll.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: 25),
    scroll.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: 25),
    scroll.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor),
    scroll.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor),
    scroll.widthAnchor.constraint(equalToConstant: stackWidth),
    scroll.heightAnchor.constraint(equalToConstant: stackWidth),
    stack.topAnchor.constraint(equalTo: scroll.topAnchor),
    stack.bottomAnchor.constraint(equalTo: scroll.bottomAnchor),
    stack.leadingAnchor.constraint(equalTo: scroll.leadingAnchor),
    stack.widthAnchor.constraint(equalToConstant: stackWidth),
    ])

bottomContainer在情节提要中创建。 stackHeight的计算值比bottomContainer的高度小50,并且stackWidth是可变的,但是即使大于bottomContainer也不会滚动。感谢您的帮助

1 个答案:

答案 0 :(得分:0)

尝试一下

var screenHeight = UIScreen.main.bounds.height
var screenWidth = UIScreen.main.bounds.width

let scroll = UIScrollView()
scroll.contentSize = CGSize(width: screenWidth, height: screenHeight)

let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .equalSpacing
scroll.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
scroll.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    scroll.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: 25),
    scroll.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: 25),
    scroll.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor),
    scroll.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor),
    scroll.widthAnchor.constraint(equalToConstant: stackWidth),
    scroll.heightAnchor.constraint(equalToConstant: stackWidth),
    stack.topAnchor.constraint(equalTo: scroll.topAnchor),
    stack.bottomAnchor.constraint(equalTo: scroll.bottomAnchor),
    stack.leadingAnchor.constraint(equalTo: scroll.leadingAnchor),
    stack.widthAnchor.constraint(equalToConstant: stackWidth),
    ])
scroll.contentSize = CGSize(width: stackWidth, height: stackHeight)
bottomContainer.addSubview(scroll)