Tiisetso Tjabane
Tiisetso Tjabane

Reputation: 2106

Swift UITextView invisible with contraints

I am adding a UITextView to the screen and adding the constraints but it does not show up on the view.

class ViewController: UIViewController {

    let balanceTitle: UITextView = {
        let textView = UITextView();
        textView.text = "hello balance";
        textView.translatesAutoresizingMaskIntoConstraints = false;
        textView.textColor = .red;
        textView.backgroundColor = .gray;
        return textView;
    }()

    let labelTitle: UILabel = {
        let lblView = UILabel();
        lblView.text = "mmsmsmsmsmsmsmsm";
        lblView.textColor = .red;
        lblView.translatesAutoresizingMaskIntoConstraints = false;
        return lblView
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        //view.backgroundColor  = .gray
        //view.addSubview(balanceTitle)
        view.addSubview(balanceTitle);

        balanceTitle.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true;
        balanceTitle.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true;
        balanceTitle.heightAnchor.constraint(equalToConstant: 400).isActive = true;
    }


}

Below is the results that I get after running the code. enter image description here

Upvotes: 0

Views: 211

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need to add width constraint

NSLayoutConstraint.activate([ 
    balanceTitle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    balanceTitle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    balanceTitle.heightAnchor.constraint(equalToConstant: 400),      
    balanceTitle.widthAnchor.constraint(equalToConstant: 200) 
])

Or like this for a proportional value with view

balanceTitle.widthAnchor.constraint(equalTo:view.widthAnchor, multiplier: 0.8)

Upvotes: 1

Related Questions