Chapter 16 - Static Cell - viewWithTag

I created static cells with 3 rows in 1 section and tag them with 1,2,3 respectively.

However, I tried to find those cells by using method viewWithTag but found nil.

May I know how to solve it?

image

image

Many thanks!!!
Ricky

The load event is a bit too early to access tableview cells using viewWithTag().

Try putting your code in viewDidAppear instead:

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //...
  }

1 Like

It works! Many thanks!

But I get confused about the timing to access the tableview cells…

This time I put a label in the static cell (row 1, section 0) and tag “1”.

I tried to run the codes in viewDidLoad and it worked. The text of the label can be set.

May I know why and how it works?

image

The static table cells that you defined on the storyboard are assembled during the load, as you have discovered. It is the assembly of the table view itself that is delayed.

That’s because your table view controller class is the datasource for the tableview. You can override methods to control how many sections and rows are displayed, for instance. So after the load, it calls those methods, using the default if you didn’t override them.

You can see this in action of you override numberOfRowsInSection, like this:

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
      return 2
    } else {
      return super.tableView(tableView, numberOfRowsInSection: section)
    }
  }

This will cause it to display only two rows, even though you defined 3 rows in the storyboard.

It has to wait till all that is done, before adding the table cells to the tableView itself. Until then, it won’t be able to find the cells using tableView.viewWithTag().

1 Like

Thanks for the detailed explanation! I appreciate that!!! :slight_smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.