錯誤代碼
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *message = [dataSource_ objectAtIndex:indexPath.row];
UIAlertView *alert = [[UIAlertView alloc] init];
alert.message = message;
[alert addButtonWithTitle:@"OK"];
[alert show];
}
問題
- 方法名錯誤:
didDeselectRowAtIndexPath 是**取消選中**時調用,非選中時調用。
- 選中時應用
didSelectRowAtIndexPath。
- 邏輯:點擊第 1 行 → 未觸發選中代碼;點擊第 2 行 → 觸發第 1 行的
didDeselect,顯示第 1 行數據。
正確代碼
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *message = dataSource_[indexPath.row];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
[tableView deselectRowAtIndexPath:indexPath animated:YES]; // 取消高亮
}
補充
UIAlertView 已棄用 (iOS 9+),改用 UIAlertController。
- 記得
deselectRowAtIndexPath:animated: 讓選中高亮動畫消退。