Mr Riksson Mr Riksson - 6 months ago 21
iOS Question

2 line text UIButton

I have a UIButton and the text of the button is filled by a randomiser.
However my problem is that sometimes the number of characters in a text is too many, leading to the button now showing the whole text.

Would it be possible to check if the characters are too many and then have it drop the rest of the text to another text line? So basically having to text lines instead of one for the UIButton?

Answer

Objectivc-C

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2;
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if u need

else use this

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

Swift

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping
button.titleLabel.numberOfLines = 2
button.titleLabel.textAlignment = .Center

else use this

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping
button.titleLabel.textAlignment = .Center
button.setTitle("Line1\nLine2", forState: .Normal)
Comments