Azulath
Azulath

Reputation: 136

Adding constraints to a TextView does not work in Swift

Im using XCode 6.1 and I'm trying to add constraints to a TextView. I've already successfully acomplished it by adding these lines of code to viewDidLoad() function of my ViewController:

    myButton.backgroundColor = UIColor.orangeColor()
    myButton.setTitle("New test old button", forState: .Normal)
    self.view.addSubview(myButton)
    myButton.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addConstraint(NSLayoutConstraint(item: myButton, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 20.0))
    self.view.addConstraint(NSLayoutConstraint(item: myButton, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 200.0))

But when I try to do the same with a TextView I can not see it on the iOS-Simulator's screen:

    var textView = UITextView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
    textView.text = "My test text!"
    textView.sizeToFit()
    textView.backgroundColor = UIColor.purpleColor()
    self.view.addSubview(textView)
    textView.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 10.0))
    self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 400.0))

If I'm deleting the three constraints specific lines, the TextView is created, but I need these constraints in order to properly format everything.

Does someone know what I'm doing wrong?

Upvotes: 1

Views: 1954

Answers (1)

vacawama
vacawama

Reputation: 154631

You need to add constraints for the width and height of your text view:

self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Width, relatedBy: .Equal,
   toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 300.0))

self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Height, relatedBy: .Equal,
    toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 300.0))

Upvotes: 2

Related Questions