Search code examples
iosswiftconstraintsnslayoutconstraintswift4

Text won't show with constraints added


So here is my current code for the viewdidload and the setup view func

    override func viewDidLoad() {
        super.viewDidLoad()



        view.addSubview(bearImageView)
        view.addSubview(descriptionText)
        view.addSubview(startButton)

        setupView()

    }

    @objc private func start() {

    }

private func setupView() {
    bearImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    bearImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
    bearImageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    bearImageView.heightAnchor.constraint(equalToConstant: 250).isActive = true

    descriptionText.topAnchor.constraint(equalTo: bearImageView.bottomAnchor, constant: 10).isActive = true
    descriptionText.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    descriptionText.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

    startButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    startButton.topAnchor.constraint(equalTo: descriptionText.bottomAnchor, constant: 140).isActive = true
    startButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
    startButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
    }

Both the bearimage and button constraints work fine (minus flipping the phone horizontally but ill fix that later) however the text just refuses to show. The text are made programmatically for istance let descriptionText = UITextView = {...}() and etc. Any of you guys have an idea?


Solution

  • If you look closely you have missed the Height Constraint for your UITextView. If you're using a UILabel or UITextField they don't need a height constraint and can calculate their height based on it's inner contents but UITextView is not going to do that because it will start scrolling if the contents is more than it's height and that's why it can not set the height based on it's inner contents and it's height is zero by default.

    add a HeightConstraint to your UITextView as well.

    // This will fix your problem
    descriptionText.heightAnchor.constraint(equalToConstant: 120).isActive = true