Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding constraints programmatically in UIView with UITextView

I added constraints programmatically in my UITextView, but trailing and bottom constraints are not working correctly. others work fine. I think UITextView frame size is not correct.

I just want to add margin in my UITextView programmatically.

My code is

    let textView = UITextView()
    self.view.addSubview(textView)

    var constraints = [NSLayoutConstraint]()

    constraintTop = NSLayoutConstraint(item: textView,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1.0,
        constant: 10)
    constraints.append(constraintTop)

    constraintBottom = NSLayoutConstraint(item: textView,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1.0,
        constant: 10)
    constraints.append(constraintBottom)

    constraintLeft = NSLayoutConstraint(item: textView,
        attribute: NSLayoutAttribute.Leading,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Leading,
        multiplier: 1.0,
        constant: 10)
    constraints.append(constraintLeft)

    constraintRight = NSLayoutConstraint(item: textView,
        attribute: NSLayoutAttribute.Trailing,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Trailing,
        multiplier: 1.0,
        constant: 10)
    constraints.append(constraintRight)

    self.view.addConstraints(constraints)
like image 862
naohide_a Avatar asked May 30 '26 03:05

naohide_a


1 Answers

You can fix this in one of two ways:

  1. Change the constant to -10 for your bottom and trailing constraints.

or

  1. Switch the order of the item: and toItem: values in the bottom and trailing constraints. That is, make item: self.view and toItem: textView for the bottom and trailing constraints. This is how it is done if you set the constraints in the StoryBoard.
like image 172
vacawama Avatar answered May 31 '26 17:05

vacawama