对 Superview 边缘的编程自动布局约束

Programmatic Auto Layout Constraints to Edges of Superview

我在 Xcode 的故事板编辑器中做了很多自动布局,但我很少用代码做任何事情。在一个特定实例中,我需要创建与这些约束等效的程序:

这些约束被添加到 textView 并且父视图是另一个名为 commentBox 的视图。到目前为止我已经试过了,但是代码感觉多余并导致约束冲突的自动布局错误:

//Trailing
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .trailing, relatedBy: .equal, toItem: cell.commentBox, attribute: .trailing, multiplier: 1, constant: 15))
//Leading
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .leading, relatedBy: .equal, toItem: cell.commentBox, attribute: .leading, multiplier: 1, constant: 15))
//Bottom
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: cell.commentBox, attribute: .bottom, multiplier: 1, constant: 10))
//Top
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: cell.commentBox, attribute: .top, multiplier: 1, constant: 10))

知道我做错了什么吗?谢谢!

试试这个:

commentBox.addSubview(textView)

textView.translatesAutoresizingMaskIntoConstraints = false

textView.topAnchor.constraint(equalTo: commentBox.topAnchor, constant: 10).isActive = true
textView.bottomAnchor.constraint(equalTo: commentBox.bottomAnchor, constant: -10).isActive = true
textView.leadingAnchor.constraint(equalTo: commentBox.leadingAnchor, constant: 15).isActive = true
textView.trailingAnchor.constraint(equalTo: commentBox.trailingAnchor, constant: -15).isActive = true