TheTeacher33
TheTeacher33

Reputation: 151

How can I position an imageView and a label in a stackView in a way that enables me to resize them according to their state?

I am coding a quiz app. The questions are shown in a tableView where there are 2 kind of cells.QuestionCell and MultipleChoiceCell.For each question I have a QuestionCell and 4 MultipleChoiceCells.

The problem:

This is how multipleChoiceCells should look like if the cells consist of text.

Text Question

and this is how they should look like if they consist of photos.

Photo Question

this is a multipleChoiceCell

multipleChoiceCell

Even if the choices consist of photos at the very least the label which is next to the imageView will show "A) or "B)" or "C)" or "D)" for every question. Also the imageView's width and height is 150.

And if the multipleChoiceCell consists of text and no image for that question then it should use all the width of the stackView.

I have tried many different approaches with or without using stackViews in the last 8 hours but could not find a solution. The closest I ever come to a solution was without using a stackView but it failed on the iPhone 5s screen size. The screenshots I have shown above were from that solution on my iPhone X.

How do I solve this? Please shed me some light...

Edit:When stack view is used the below problem occurs.MultipleChoiceCell has images but I still need the label to show "A" "B" "C" or "D".Also the label takes too much space no matter what I do.

Problem with StackView

Upvotes: 0

Views: 1590

Answers (1)

David Steppenbeck
David Steppenbeck

Reputation: 1094

I think using UIStackView is the way to go. You just have to make sure certain constraints and hugging priorities are set properly to get your desired look. If I've understood you correctly, I think this is what you are want:

enter image description here enter image description here

I embedded the label and imageView in a horizontal stackView with properties:

stackView.alignment = .fill
stackView.distribution = .fill
imageView.contentMode = .left

Also, imageView has a fixed height constraint of 150, but no width constraint. The label has a horizontal hugging priority of 751.

(i) In the case where you want text in the label to fill the whole width (but no image), do this:

imageView.isHidden = true
label.numberOfLines = 0

(ii) In the case where you want short text, such as A) etc, and an image, do this:

imageView.isHidden = false
label.numberOfLines = 1

Upvotes: 2

Related Questions