0

I have my UILabel code as below. It works find showing UILabel in my ViewController.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let myText = UILabel()
        myText.text = "Testing"
        view.addSubview(myText)
        myText.translatesAutoresizingMaskIntoConstraints = false
        myText.backgroundColor = .green
        NSLayoutConstraint.activate([
            myText.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myText.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }
}

However if I change to UITextView as below, nothing appears. What did I do wrong?

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let myText = UITextView()
        myText.text = "Testing"
        view.addSubview(myText)
        myText.translatesAutoresizingMaskIntoConstraints = false
        myText.backgroundColor = .green
        NSLayoutConstraint.activate([
            myText.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myText.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }
}
Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

2

you have to give height and width to UITextView or give Top, Bottom, Left, Right anchor.

NSLayoutConstraint.activate([
        myText.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        myText.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        myText.heightAnchor.constraint(equalToConstant: "Your height"),
        myText.widthAnchor.constraint(equalToConstant: "Your width")
])

Thanks

Habin Lama
  • 529
  • 5
  • 19
  • Thanks @Habin Lama. In the event I just want the height and width to auto wrap around the text that it contains (e.g. like wrap_content of Android), like what it does for the UILabel, how could I achieve that? – Elye Feb 23 '20 at 04:11
  • 1
    I guess to Wrap the UITextView, the answer is in https://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content – Elye Feb 23 '20 at 05:09
  • 1
    Yes that answer should help you. – Habin Lama Feb 23 '20 at 05:35
  • It's confusing that the need to setup basic UILabel and UITextView differs. Hope my question and your answer would help others in this confusing state. Upvote and tick your answer. Thanks! – Elye Feb 23 '20 at 05:37