user4806509
user4806509

Reputation: 3011

Issue with UILabel center text alignment at different font sizes in Xcode Swift

This is an issue with UILabel in iOS7 and iOS8, it does not present in iOS9. This odd UILabel behaviour is experienced with different fonts, in Xcode versions 6 and 7 with Swift, using the simulator and device.

Problem:

I have a UILabel that has a center text alignment. At different font sizes, some lines of text stop being center aligned and snap to left alignment. It is subtle but noticeable.

In the images below:

LEFT: all lines of text are centered neatly.

MIDDLE: after increasing the font size, the third line from the top snaps more to the left instead of remaining centered. (Notice more blue space on right.)

RIGHT: after increasing the font size a little more, both the second and third line from the top snap to the left instead of remaining centered. (Notice more blue space on right.)

enter image description here

Questions:

  1. What explains what might be the cause of this unusual alignment behaviour in iOS7 and iOS8 but not iOS9?
  2. How can I ensure that all lines are forced to remain center aligned perfectly regardless of the font type or font size used?
  3. What is the bug fix or work around for this in iOS7 and iOS8 so that apps created using UILabel centre aligned don’t feature the bug?

Upvotes: 1

Views: 1374

Answers (1)

SwiftArchitect
SwiftArchitect

Reputation: 48514

Use UITextView

With all due respect, it is my experience that UILabel is plagued with bugs when it comes to multiple lines (Line count other than 1).
Starting, but not limited to sizing cells containing such labels hardly able to predict its footprint1.

Use UITextView, non editable, scrolling disabled (that is the key). You will achieve the same effects, with more control over the final appearance.


1 See note 3 on this Stack Overflow UILabel answer.

Upvotes: 1

Related Questions