Find the UITableViewCell of an element in my Model

108 views Asked by At

I would like to scroll in my tableView to a specific item. I know which item this is in my model. However, I can't be certain in which cell/indexPath it will be displayed for various reasons (the model may be filtered and sorted before displayed; the tableView may be grouped; etc.)

I was thinking of checking for the element in the cellForRowAtIndexPath tableView function and if found setting a global variable of type UITableViewCell or NSIndexPath. I'm reluctant, though, to do this - It is somewhat ugly solution due to handling global variables (not very functional / "spaghetti code".)

What is the best practice of finding the cell (or indexPath) of a specific element in my model?

1

There are 1 answers

1
kbpontius On

Generally, the UITableView is driven by a designated data source. Often this is an array of results or something similar. In turn, the position of the item in the array is mapped to a certain indexPath for your TableView, unless you're sorting on some value.

Searching an array would be much simpler than the one you've suggested, but until we know more about how your TableView's data source is structured it's difficult to suggest an optimal approach.

If you're going to try my suggested generic approach (again, assuming it's similar to an array), put a method call in tableView:numberOfRowsInSection: (which is fired when the data source is prepared but the cells haven't been rendered). This will give you a chance to search your data once per refresh.

Review this post for more info:
How to tell when UITableVIew has completed ReloadData?

Let me know if you have more details and I can be more specific.