Search code examples
swiftautolayoutnslayoutconstraint

Programmatic Auto Layout Constraints to Edges of Superview


I have done quite a bit of auto layout in Xcode's storyboard editor, but I rarely ever do anything in code. In one particular instance, I need to create the programmatic equivalent to these constraints:

enter image description here

These constraints are added to textView and the superview is another view called commentBox. I've tried this so far, but the code feels redundant and results in an auto layout error of conflicting constraints:

//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))

Any idea what am I doing wrong? Thanks!


Solution

  • Try this:

    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