0

After much searching I have started to give up

I have an iOS app (swift) that asks the user a series of questions and answers. The questions and answer are downloaded from a JSON file. There will always be 1 question per page but a varied number of answers. So the answers are UIButtons added to a UIStackView which is created in the xib. Here's the slight problem.

If I create an answer with more than 1 line (i.e. It has a line break in it), it will create a new line in the UIButton.titleLabel and expand the UIButton to fit. However, if the answer is long and spans over more than 1 line the UIButton does not expand. I have line wrap enabled to the label wraps correctly, however the button doesn't seem to realise it's width constraint within the UIStackView and therefore assumes it can display 1 long line of text and creates it's height accordingly - even when I call the ever trusty sizeToFit()!!!

I assume there is a simple setting such as "contentWidth" I am missing.

P.S. I would prefer not to calculate the size and manually set the height of the button. I want it to work with rotation as well which of course resizes the width

3
  • 1
    preferredMaxLayoutWidth could solve your problem.
    – dasdom
    Commented Apr 4, 2016 at 14:26
  • Thanks @dasdom did not solve it however. More interestingly preferredMaxLayoutWidth was in fact completely ignored (even when being set just as a constant like 5.) Setting "Baseline Relative" on my StackView made preferredMaxLayoutWidth be noticed however didn't do anything for changing my height. Will continue searching for answers! Commented Apr 4, 2016 at 18:01
  • Any fresh insight on this problem? Commented Mar 15, 2019 at 21:03

1 Answer 1

0

Okay I never found a fix for making the Button resize to it's own UILabel size correctly, it seems it constantly sees the text being able to fit to one line and work.

I did overcome the problem by replacing my UIButton with a UILabel. The UILabel then has addGestureRecognizer(UITapGestureRecognizer()) and of course userInteractionEnabled = true

It's not the way I would like it to be but will keep my client happy until the next update to UIStackView!

Not the answer you're looking for? Browse other questions tagged or ask your own question.