我有一个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
}
我想念什么?
答案 0 :(得分:3)
您需要添加
scrollView.addSubview(textView)
textView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0).isActive = true
在设置约束之前,同样如果您在IB内设置scrollview约束,也不要设置
// comment scrollView.translatesAutoresizingMaskIntoConstraints = false