Dengekiko
Dengekiko

Reputation: 63

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?

Upvotes: 0

Views: 50

Answers (2)

Khalid Afridi
Khalid Afridi

Reputation: 923

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

Upvotes: 1

Cal Stephens
Cal Stephens

Reputation: 793

It's possible the image's intrinsic content size is so large that it is expanding such that there is no more space available for the descriptionText label. Try updating the content compression resistance priority of the label to required so it cannot be compressed by the image view.

Swift 3:

descriptionText.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical)

Swift 4:

descriptionText.setContentCompressionResistancePriority(.required, for: .vertical)

Upvotes: 0

Related Questions