简体   繁体   中英

Setting Text of UITableViewCell when cell is not selected

I have a UITableViewCell that is being instantiated (in the "cellForRowAtIndexPath" method) with

[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];

When the "Accessory Button" is clicked, I have a UIDatePicker being popped that is supposed to set the text of the cell to the date being selected. The Picker shows up and my cell is not nil, however, I cannot see the actual text (date) of the cell until I click it (the cell, not the "accessory button").

Here is the code that is setting text:

targetCell.textLabel.text = [formatter stringFromDate:_datePicker.date];

targetCell is an instance variable being set when the method: "accessoryButtonTappedForRowWithIndexPath" is called.

Like I said, I know the text is being set in the cell because when I click the actual cell I can see the date selected in the picker.

It seems like you are trying to modify the currently displayed table view cell directly. Even if you manage to change it this way, this will still not work because when your row scrolls out of view, its corresponding cell is re-used for another row. So your changes will either be lost, or you will display something incorrectly.

The correct way of managing this is to:

  1. Change your data source, and not the cell, when a value is picked from the date picker
  2. Reload the view for the cell by either reloading
    • the whole table view using -[UITableView reloadData] , or
    • just that row using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:]

Using either of these methods will result in the table view data source's -tableView:cellForRowAtIndexPath: being called, which will update the row with a new cell. So the correct date will be displayed for this row even if it scrolls out of view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM