Search code examples
iosswiftcocoa-touchadaptive-layout

ios: text does not wrap correctly on iPhone 5S and earlier (4 inch and smaller devices)


I have a label that is supposed to wrap around. There are 4 constraints on it (top/bottom and leading/trailing - no other constraints). The label wraps around correctly on iPhone 6 i.e. 4.7" screen and iPhone 6 Plus i.e. 5.5" screen, But gets cut off on the right edge on 4" inch or smaller screen devices. Please see the screenshot below.

enter image description here

It's as if it thinks available width is more than actual device width. any ideas? (sorry can't post image inline because it requires at least 10 rep)

FWIW: Here are the constraints on the label (I am writing these in pseudo code because these are set in IB).

label.top = top margin
label.bottom = bottom margin
label.leading = leading margin
label.trailing = trailing margin

Solution

  • I found out what the issue was, This label was in a cell of type TextCell, and here's what I was doing in TextCell's layoutSubviews method:

    override func layoutSubviews() {
        super.layoutSubviews()
    
        // ... snip ...
    
        self.text.preferredMaxLayoutWidth = 375 // This is the offending line
    }
    

    Change preferredMaxLayoutWidth to a sane value (e.g. CGRectGetWidth(self.label.frame)) fixed it.

    Please note that the above is a simplification of what the issue was, the point being when you have issues with a self sizing label in Cocoa Touch, always check that preferredMaxLayoutWidth is being set to correct value

    Here's a related question (pointed me in the correct direction): UILabel not wrapping text correctly sometimes (auto layout)