2012-10-12 35 views
6

Tôi có một UITableView với các ô tùy chỉnh trong đó. Ô tuỳ chỉnh này trông giống như ô bình thường với Kiểu "Chi tiết bên trái". Nhưng ô tùy chỉnh của tôi có nhãn chi tiết và trường văn bản, cho phép người dùng chỉnh sửa văn bản. Tôi có một nút Lưu nơi tôi muốn lưu tất cả dữ liệu mà người dùng đã nhập. Tôi tạo ra ô tùy chỉnh bằng cách sử dụng hướng dẫn này: http://agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/#comment-4883indexPathForCell của UITableView: trả về luôn 0 như indexPath.row

Để lấy dữ liệu người dùng, tôi đặt đại biểu của trường văn bản cho bộ điều khiển xem bảng (self) và triển khai phương thức textFieldDidEndEditing:. Trong phương thức này, tôi yêu cầu khung nhìn cha của trường văn bản (= ô) và yêu cầu indexPath của ô này. Vấn đề là, tôi luôn nhận được 0 cho indexPath.row, bất kể ô nào tôi chỉnh sửa. Tôi đang làm gì sai?

Đây là mã của tôi:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier] forIndexPath:indexPath]; 
if (cell == nil) { 
    [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
    cell = self.customCell; 
    self.customCell = nil; 
} 

cell.label.text = @"Some label text"; 
cell.editField.delegate = self; 
cell.accessoryType = UITableViewCellAccessoryNone; 

return cell; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
CustomCell *cell = (CustomCell *) textField.superview; 

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row); 
... 
} 

EDIT: Tôi chỉ phát hiện ra, rằng indexPath trả lại là con số không. Vì vậy, nếu nó là nil tôi nhận được các giá trị tiêu chuẩn 0, thats okay. Nhưng bây giờ: Tại sao tôi nhận được nil cho indexPath?

+0

Đây là một chủ đề tương tự cho biết lý do cho http://stackoverflow.com/questions/6930026/tableviewindexpathforcell-returns-nil –

Trả lời

6

Tôi chỉ tìm thấy giải pháp bản thân mình. Tôi tìm thấy mã cho superview trong stackoverflow, vì vậy tôi chỉ cần sao chép nó. Nhưng điều đó không hiệu quả. Bạn cần phải thực hiện hai người giám sát như sau:

CustomCell *cell = (CustomCell *) textField.superview.superview; 

Bây giờ nó hoạt động tốt!

0

thể bạn chỉ cần thêm một tài sản index để CustomCell của bạn và cư nó với indexPath.row bên (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

+0

Ý tưởng hay, tôi đã làm điều này nhưng tôi gặp lỗi khi nói "bộ chọn không được nhận dạng được gửi đến ví dụ. .. [UITableViewCellContentView indexPath] "(Tôi gọi là thuộc tính indexPath). Vì vậy, tôi là một chút bối rối về lý do tại sao tế bào bây giờ là một UITableViewCellContentView và không phải là CustomCell của tôi. – tester

Các vấn đề liên quan