Search code examples
objective-cios4xcode4

delete UITableViewCell programmatically


I was wondering if it's possible to remove empty cells (empty = cells with no textLabel) after all the cells are created in a UITableView.


Solution

  • Why do you have empty cells? Are you using a consistent technique to control both the number of cells in your table and the content of those cells?

    If you're using a UITableViewController, then your controller is automatically declared as the tableview's datasource. If you're using a UIViewController, then you'll declare it as comforming to the UITableViewDataSource protocol (and connect it up in Interface Builder).

    Either way, as the tableview's datasource, your controller is required to implement two methods: – tableView:cellForRowAtIndexPath: – tableView:numberOfRowsInSection:

    Presumably you're providing the data for the tableview with an array or other means inside -tableview:cellForRowAtIndexPath:. Inside this method the cell's label will be set from an entry in your array. And inside tableView:numberOfRowsInSection: you'll be doing something like [myArray count] to return the number of cells. tableview:cellForRowAtIndexPath will be called as many times as you tell it to (dictated by what you provide in tableview:numberOfRowsInSection:). If the datasource array changes, and you'd like to reflect the changes in your tableview, then you can call

    [self.tableview reloadData];  //if inside a UITableViewController
    
    [self.myTableViewOutlet reloadData];  //if inside a UIViewController
    

    Note that reloadData reloads the entire tableview, so in some cases this may be computationally expensive. In this case, instead of calling reloadData you can focus on individual rows with the method: deleteRowsAtIndexPaths:withRowAnimation: (see UITableView Class Reference)