代码中添加的UIScrollView不再滚动

时间:2017-11-16 09:09:18

标签: ios swift uiscrollview

这就是我在代码中所做的:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let scroll = UIScrollView()
    scroll.backgroundColor = .yellow
    scroll.translatesAutoresizingMaskIntoConstraints = false

    let leading = NSLayoutConstraint(item: scroll, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    let trailing = NSLayoutConstraint(item: scroll, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    let top = NSLayoutConstraint(item: scroll, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
    let bottom = NSLayoutConstraint(item: scroll, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)

    view.addSubview(scroll)
    view.addConstraints([leading, trailing, top, bottom])

    let label = UILabel()
    label.text = "helloo, my new text"
    label.backgroundColor = .orange
    label.translatesAutoresizingMaskIntoConstraints = false

    let leading2 = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: scroll, attribute: .leading, multiplier: 1, constant: 0)
    let trailing2 = NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: scroll, attribute: .trailing, multiplier: 1, constant: 0)
    let top2 = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: scroll, attribute: .top, multiplier: 1, constant: 200)
    let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 400)
    let height2 = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 600)

    scroll.addSubview(label)
    label.addConstraint(height2)
    scroll.addConstraints([leading2, trailing2, top2, bottom2])
    scroll.layoutIfNeeded()
}

这是它在屏幕上的样子:

enter image description here

但我根本无法滚动它。为什么?这有什么不对?

我知道有很多关于SO的例子和问题,但是甚至都没有。

1 个答案:

答案 0 :(得分:1)

你给了标签错误的底部约束。将常量值从400更改为0.

let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0)

enter image description here