问题
I am attempting to select, in the view did appear method, a table cell programatically.
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
my delegate,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
does not get called.
The delegate gets called if i select the cells in the simulator with a mouse, however, just not programmatically.
Why can this be?
回答1:
Because that's how the framework works. Try reading the docs. That's what they are for!
selectRowAtIndexPath:animated:scrollPosition:
Selects a row in the receiver identified by index path, optionally scrolling the row to a location in the receiver... Calling this method does not cause the delegate to receive a
tableView:willSelectRowAtIndexPath:
ortableView:didSelectRowAtIndexPath:
message.
That's pretty easy to understand. The delegate method didSelectRowAtIndexPath:
is not called if you select the row in code (programmatically). It is called only if the user selects the row.
And this makes perfect sense, because:
If you are selecting the row in code, you might not want the delegate method triggered.
If you do want the delegate method triggered, since you are in your own code, you can just call it.
You don't need the delegate method in order to learn that the row was selected, because you selected it in code - you cannot not know!
来源:https://stackoverflow.com/questions/16504078/cannot-select-uitableviewcell-programmatically