首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableView didDeselectRowAtIndexPath 導致彈窗顯示上一條數據的修正

     編輯:程式設計綜合問答

錯誤代碼


- (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: 讓選中高亮動畫消退。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved