-1

I've got a UIButton, it's a simple segue to another page.

I've set Title to attributed and then selected word wrap. This works fine, the second word wraps down to the next line.

However, it is all left justified. When I select "Align Centre" (using the buttons just under the "Title", the word wrap no longer works and simply runs .... so you can't see it all. (e.g. "next pa" instead of "next page")

Am I missing something here? It seems like such a trivial thing to do! There's an old answer here can't get word wrap to work on UIButton but it's both old and uses code - surely you don't need code to centre the button text if you want to word wrap it to 2 lines!?

nc14
  • 539
  • 1
  • 8
  • 26

2 Answers2

3

I've set Title to attributed and then selected word wrap. This works fine, the second word wraps down to the next line. However, it is all left justified.

Once you've decided to use an attributed string, you must do everything with the attributed string. So give your attributed string a paragraph style that centers the text.

    let para = NSMutableParagraphStyle()
    para.alignment = .center
    para.lineBreakMode = .byWordWrapping
    let s = NSAttributedString(
        string: "Hello World", attributes: [.paragraphStyle : para])
    self.button.setAttributedTitle(s, for: .normal)

You will also need to set the button's title label to allow multiple lines.

    self.button.titleLabel?.numberOfLines = 0

Result:

enter image description here

surely you don't need code to centre the button text if you want to word wrap it to 2 lines!?

Not to center it, no; you can set the centering in the storyboard. So you could eliminate the first batch of code and configure it in the storyboard. But you must use code to turn the title label into a multiline label:

    self.button.titleLabel?.numberOfLines = 0

There is no way to do that in the storyboard, because you have no access to the title label there.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

I've just been playing round with this and I've found it works if you set it to 'character wrap' rather than 'word wrap' once you've selected centre alignment.

If anyone has a better solution please add it, as I guess this might have issues if you slightly change the width etc when using auto layout for different screen sizes etc if you want it to adapt its width so this might not be the best solution but it does work

nc14
  • 539
  • 1
  • 8
  • 26