awakeFromNib, layoutSubviews, dequeueReusableCellWithIdentifier and what happens in what order

If you have customized code in your UITableViewCell subclass like myself, you usually have some

If you have customized code in your UITableViewCell subclass like myself, you usually have some startup code for the cell, usually setting some constraints, or colors of text, default placeholder, etc. It generally doesn't matter whether this code goes in awakeFromNib or layoutSubviews, as long as what you do after dequeueReusableCellWithIdentifier doesn't depend on logic in either of these startup methods.

In the case where it does, you need to know which one happens in which order, in my case I'm using a custom UITextView that has placeholder text, via a nice blog post on how to do that:

https://grokswift.com/uitextview-placeholder/

The issue was that when opening a form to fill out for a new document the text is empty, so you need placeholder text. On top of this I have a label that needs to show (alpha = 1) when text from the user is inputted. When no text exists in the TextView the label needs to animate away and the Placeholder text needs to appear.

So you can see the possible logic branches I have, the issue was that at first launch of the cell before any text is set (if text already exists), my custom placeholder UITextView needs to get setup with constraints, placeholder text, placeholder text color, etc. But when the text already exists it needs to be set after the deque method is called, which then should disable the label and put the real text in the TextView (thus disabling the placeholder).

I got in a bind because I couldn't figure out which of these 3 methods run in which order, in this case, print out to console obviously shows you.

Here's the 3 important parts of code:

(called from the UITableViewController)

let cell = tableView.dequeueReusableCellWithIdentifier(notesTextViewCellId)

(inside the UITableViewCell subclass)

override func layoutSubviews() {
    super.layoutSubviews()
    print("layoutSubviews called")

    // do startup code here?
}

override func awakeFromNib() {
    super.awakeFromNib()
    print("awakeFromNib called")

    // or here?
}

or both?

In my case it was both.

Constraints needed to be in the awakeFromNib() and setting the placeholder logic needed to be in the layoutSubviews() as that happens AFTER the cell is dequed, where the awakeFromNib() happens before.

Here's the order when printed out to the console:

awakeFromNib called
notesCell dequeued
layoutSubviews called

Comments

Popular posts from this blog

Gradient UINavigationBar in Swift

Simple Xamarin iOS Keychain code

How to shuffle an array in Swift