设置约束时抛出错误isActive = true

时间:2018-12-04 12:03:31

标签: swift constraints nslayoutconstraint

我有一个scrollView,并且在其中添加了textView。我想将文本视图居中到schollView。该代码在行textView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0).isActive = true上引发错误,但也只有在我调用.isActive = true时才发生错误。

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 1000))
    textView = text
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.sizeToFit()
    textView.isScrollEnabled = false

    scrollView.translatesAutoresizingMaskIntoConstraints = false
    textView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0).isActive = true
}

我想念什么?

1 个答案:

答案 0 :(得分:3)

您需要添加

scrollView.addSubview(textView)
textView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0).isActive = true

在设置约束之前,同样如果您在IB内设置scrollview约束,也不要设置

// comment scrollView.translatesAutoresizingMaskIntoConstraints = false