Search code examples
iosuitableviewautolayoutuilabel

UILabel incorrectly sized in UITableViewCell (Animation after assigning text)


The text in a UILabel is flickering after being displayed, first appearing with ellipsis on a single line, then occupying the 2 lines it fits in. Notice that the cell height doesn't change.

UILabel wrap

Here is the problem:
The label "Друзъя, примите участие и наполните Коробку!" (Friends, take part and fill the boxes!) first appears truncated and misaligned as "Друзъя, примите участи..." during the view transition.

animation

This happens only on iPhone 4s with iOS 8.1. All manipulation with Label (except text assigning) happens in the Storyboard.

What is causing this flickering?


Solution

  • Assuming you are changing the test in cellForRowAtIndexPath, and further assuming this does not happen with all strings, only some with certain length, then this is an iOS bug.

    See lengthy discussion on this Stack Overflow UITableViewCell post, and a possible workaround:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.setNeedsLayout()
        tableView.layoutIfNeeded()
        tableView.reloadData()
    }
    

    Notes

    1. I have also noticed that using a small value for estimatedRowHeight such as 20, which is not as tall as the smallest cell, in combination with the doubled reloadData() was also beneficial.

    2. You will need to invoke an extra reloadData() prior setNeedsLayout() when changing the cell width, such as toggling tableView.editing

    3. A robust alternative to tinkering with a label is to use a non Editable, non Selectable, none Capitalization, noScrolling enabled, no Show Horizontal & Vertical Indicator, no Bounce UITextView.


    Exercise this bug, and try out the various workarounds:

    ► Find this solution on GitHub and additional details on Swift Recipes.