程序化自动布局约束到Superview的边缘

时间:2019-02-07 04:54:26

标签: swift autolayout nslayoutconstraint

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

enter image description here

这些约束已添加到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))

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

1 个答案:

答案 0 :(得分:1)

尝试一下:

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