Ошибки UITableView InsertRowsAtIndexPaths
-
13-11-2019 - |
Вопрос
Я просмотрел почти все результаты поиска, но моя ошибка не исчезла.У меня есть табличное представление, инициализированное двумя разделами и одной строкой в каждом (из массива).У меня есть кнопка для просмотра заголовка раздела.При нажатии кнопки я хочу добавить строку в первый раздел.Вот код:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell*)[self.myTableView dequeueReusableCellWithIdentifier:@"DetailCell"];
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
cell.backgroundColor=[UIColor clearColor];
return cell;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
switch (section) {
case 0:
btnReleases=[UIButton buttonWithType:UIButtonTypeCustom];
[btnReleases setFrame:CGRectMake(10, 0, 30, 39)];
[btnReleases setImage:[UIImage imageNamed:@"buttonr.png"] forState:UIControlStateNormal];
[btnReleases addTarget:self action:@selector(loadReleases) forControlEvents:UIControlEventTouchUpInside];
return btnReleases;
break;
case 1:
btnLinks=[UIButton buttonWithType:UIButtonTypeCustom];
[btnLinks setFrame:CGRectMake(10, 0, 30, 39)];
[btnLinks setImage:[UIImage imageNamed:@"buttonl.png"] forState:UIControlStateNormal];
[btnLinks addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
return btnLinks;
break;
default:
break;
}
}
-(void)loadReleases
{
[self.myTableView beginUpdates];
[arr addObject:@"WTF"];
NSArray *insert0 = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]]; NSLog(@"%@",insert0);
[self.myTableView insertRowsAtIndexPaths:insert0 withRowAnimation:UITableViewRowAnimationBottom];
[self.myTableView endUpdates];
}
Вот ошибка:
* Ошибка утверждения в -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableView.m:1046
Решение
Поскольку вы используете [arr count]
в качестве возвращаемого значения для tableView:numberOfRowsInSection:
, в конце beginUpdates…endUpdates
блокирует tableView, ожидая, что в каждом из разделов tableView будет две строки, но ваш вызов insertRowsAtIndexPaths:
указывает только на то, что строка находится в разделе 0.
Вам нужно исправить свой tableView:numberOfRowsInSection:
для возврата разных значений в зависимости от раздела:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return [arr count];
} else {
return 1;
}
}
Обратите внимание, что с вашим tableView происходит много подозрительных вещей:у вас есть два раздела, но в каждом разделе вы показываете одну и ту же строку 0.И поведение вставки в ваши разделы довольно шаткое:вы начинаете показывать только одну строку, соответствующую регистру 0 в вашем switch
, затем вы указываете, что вставляете строку в строку 0, после чего строка с регистром 0 будет отображаться в строке 0, а строка с регистром 1 — в строке 1.Таким образом, вам действительно следует вставлять строку в строку 1 вместо строки 0:
NSArray *insert0 = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]];
[self.myTableView insertRowsAtIndexPaths:insert0 withRowAnimation:UITableViewRowAnimationBottom];
Другие советы
Попробуйте с ним ниже кода
NSIndexPath *indexpath_add = [NSIndexPath indexPathForRow:0 inSection:0];
[[self myTableView] beginUpdates];
[[self myTableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexpath_add] withRowAnimation:UITableViewRowAnimationRight];
[[self myTableView] endUpdates];
.