2015-07-29 2 views
0

У меня есть UITableView с простым массивом в качестве источника данных. Я разработал специальный наконечник для специального UITableViewCell, который отображается, когда массив пуст (т.е. когда приложение запускается первым).Как перезагрузить пользовательскую ячейку представления таблицы после удаления последней строки?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if ([self.wallet count] == 0) 
     return 1; 
    else return [self.wallet count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    // If there isn't any coupon yet, then show the custom "No Coupon Yet" cell 
    if ([self.wallet count] == 0) 
     return [tableView dequeueReusableCellWithIdentifier:@"NoCouponCell" forIndexPath:indexPath]; 
    else { 
     CouponCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CouponCell" forIndexPath:indexPath]; 
     Coupon *coupon = [self.wallet objectAtIndex:indexPath.row]; 

     [cell configureForCoupon:coupon]; 
     return cell; 
    } 
} 

Так как я хотел бы добавить функциональность салфетки для удаления, я предоставил следующий метод для контроллера представления.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    [self.wallet removeObjectAtIndex:indexPath.row]; 
    // Creates a new, temporary array holding just the one index-path item 
    NSMutableArray *tmp = [[NSMutableArray alloc] initWithObjects:indexPath, nil]; 
    // Tells the table view to delete the row with a nice animation 
    [tableView deleteRowsAtIndexPaths:tmp withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

Однако, когда в представлении таблицы есть только одна строка, и я пытаюсь удалить ее, приложение падает. Зачем?

EDIT: информация об отладке сообщает, что поднят NSInternalInconsistencyException.

+0

Вы можете добавить точку останова исключение для вашего проекта и сказать нам, где именно приложение падает? – halileohalilei

+0

Другое дело, вы также удаляете элемент, соответствующий вашей ячейке, из вашего массива при удалении ячейки? – halileohalilei

+0

И какой журнал это показывает при сбое – Munahil

ответ

1
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 

    if (editingStyle == UITableViewCellEditingStyleDelete) 
    { 
     // Delete the row from the data source 
     [self.wallet removeObjectAtIndex:indexPath.row]; 

     [tableView reloadData]; // reload your table to see updates 

     // or if you what some animation use| 

     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath] 
         withRowAnimation:UITableViewRowAnimationAutomatic]; 

...


Вот фикс для cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    CouponCell *cell = [tableView dequeueReusableCellWithIdentifier:[self.wallet count] == 0 ? @"NoCouponCell" : @"CouponCell" forIndexPath:indexPath]; 

    if ([self.wallet count] > 0) 
    { 
     Coupon *coupon = [self.wallet objectAtIndex:indexPath.row]; 

     [cell configureForCoupon:coupon]; 
    } 
    return cell; 
} 
+0

Это не отображает мою собственную таблицу представления таблицы, когда источник данных пуст. – Dree

+0

@Dree, там .. я обновил свой ответ и исправил вашу 'cellForRowAtIndexPath' – 0yeoj

+0

Это сработало! Большое спасибо друг. ;) – Dree

0

Используйте это в numberOfRowsInSection функции:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

     return [self.wallet count]; 
} 

И в конце вашей commitEditingStyle функции используйте

[tableView reloadData]; 
+0

Это работает (приложение больше не разбивается), но оно не перезагружает мою пользовательскую ячейку. – Dree

+0

Чтобы перезагрузить, вы можете позвонить, [self.tableView reloadData] // использовать имя экземпляра tableview – Munahil

0

Попробуйте этот кусок кода:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    [self.wallet removeObjectAtIndex:indexPath.row]; 
    // Creates a new, temporary array holding just the one index-path item 
    NSMutableArray *tmp = [[NSMutableArray alloc] initWithObjects:indexPath, nil]; 
    // Tells the table view to delete the row with a nice animation 
    [tableView beginUpdates]; 
    [tableView deleteRowsAtIndexPaths:tmp withRowAnimation:UITableViewRowAnimationAutomatic]; 
    [tableView endUpdates]; 
} 
0

Вы возврат строки 1, если ваш массив данных wallet не имеет элементов TS:

if ([self.wallet count] == 0) 
     return 1; 
    else return [self.wallet count]; 

Но в commitEditingStyle методе вы не обрабатывать этот случай: Это означает, что можно удалить NoCouponCell. И я предполагаю, что произошел сбой, потому что вы хотите удалить объект из своего массива данных, которого нет.

[self.wallet removeObjectAtIndex:indexPath.row]; 

Решение: Используйте следующий метод делегата, чтобы определить, когда клетка может быть отредактирована: Это предотвращает метод делегата commitEditingStyle называться.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{ 
    return [self.wallet count] > 0 
} 
+0

Мне нужно вернуть 1, когда у моего массива данных нет элементов, потому что я хочу отобразить пользовательскую ячейку. – Dree

0

вы можете добавить вид на UITableView tableFooterView на Tableview источника данных, вы можете поместить В этом окне

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    if (dataArray.count == 0) { 
     UIView *view = [[UITableView alloc] initWithFrame:self.view.bounds]; 
     view.backgroundColor = [UIColor blueColor]; 
     self.tableView.tableFooterView = view; 
    } 
    return dataArray.count; 
} 
1

попробовать это в вашем коде:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
     return [self.wallet count]; 
} 
Смежные вопросы