Как удалить ячейку из статического UITableView, созданного в Storyboard
Это должно быть легко, но у меня проблемы.
У меня есть статический UITableView с ячейкой, которую я хотел бы удалить программно, если это не понадобится.
У меня есть IBOutlet для него
IBOutlet UITableViewCell * cell15;
И я могу удалить его, вызвав
cell15.hidden = true;
Это скрывает его, но оставляет пустое место, где была ячейка, и я не могу избавиться от нее.
Возможно, взломам было бы изменить его высоту до 0?
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:indexPath
{
//what would I put here?
}
Большое спасибо!
Ответы
Ответ 1
Вы не можете справиться с этим в источнике данных, поскольку со статическими таблицами вы даже не реализуете методы источника данных. Высота - это путь.
Попробуйте следующее:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell == cell15 && cell15ShouldBeHidden) //BOOL saying cell should be hidden
return 0.0;
else
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
Обновление
Похоже, что при автозапуске это может быть не лучшим решением. Существует альтернативный ответ здесь, который может помочь.
Ответ 2
Вы можете использовать tableView:willDisplayCell
и tableView:heightForRowAtIndexPath
с идентификатором ячейки, чтобы показать/скрыть статические ячейки tableview
, но вы должны реализовать heightForRowAtIndexPath
, ссылаясь на super
, а не на self
. Эти два метода работают отлично для меня:
(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier.description isEqualToString:@"cellCelda1"]) {
[cell setHidden:YES];
}
}
и
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
if ([cell.reuseIdentifier.description isEqualToString:@"cellCelda1"]) {
return 0;
}
return cell.frame.size.height;
}
Ответ 3
В зависимости от того, как должна работать ваша таблица, в вашем источнике данных вы можете реализовать tableView:numberOfRowsInSection:
, чтобы вернуть 0 строк для раздела на основе вашей необходимой логики.
Обновлено для вашего комментария:
Параметр раздела будет заселен iOS при вызове реализации, так что все, что вам нужно, - это переключатель для обработки раздела, в котором строка, которую вы ant удалили/скрыли. Пример ниже:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch(section) {
case 0: // first section of your table, change for your situation
return 0;
default:
return 0;
}
}
Ответ 4
Он для только постоянной ячейки
-(void)tableViewSearchPeopleCellHide:(BOOL)hide{
searchCellShouldBeHidden=hide;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
cell.hidden=hide;
self.searchPeople.hidden=hide;//UILabel
[self.tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (searchCellShouldBeHidden) //BOOL saying cell should be hidden
return 0.0;
else
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
Ответ 5
Первое, что вы можете сделать, это пометить ячейку из раскадровки, которую вы хотите скрыть.
Поместите некоторый стандартный номер, который вы можете идентифицировать.
Добавьте этот код.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
if (cell.tag==10) { //I have put 10 for some static cell.
cell.hidden=YES;
return 0;
}
cell.hidden = NO;
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
Ответ 6
Установите ячейку, которую вы хотите скрыть, чтобы спрятать где-нибудь в вашем коде. Добавьте этот код: (Если ваша ячейка имеет разную высоту строки, вам необходимо переопределить больше функций)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount=0;
for ( int row=0; row<[super tableView:tableView numberOfRowsInSection:section]; ++row){
NSIndexPath* path=[NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell=[super tableView:tableView cellForRowAtIndexPath:path];
if (!cell.hidden){
++rowCount;
}
}
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int realRow=-1;
for ( int row=0; row<[super tableView:tableView numberOfRowsInSection:indexPath.section]; ++row){
NSIndexPath* path=[NSIndexPath indexPathForRow:row inSection:indexPath.section];
UITableViewCell* cell=[super tableView:tableView cellForRowAtIndexPath:path];
if (!cell.hidden){
++realRow;
}
if (realRow==indexPath.row)
return cell;
}
return nil;
}
Ответ 7
Используйте индексный путь для идентификации ячейки в делегате высоты табличного представления и возврата 0
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if someCondition {
if indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 {
return 0
}
}else{
if indexPath.row == 4 {
return 0
}
}
return super.tableView(tableView, heightForRowAt: indexPath)
}