ios UITableView 设置为静态单元格。是否可以以编程方式隐藏某些单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8260267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:35:08  来源:igfitidea点击:

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

iosobjective-cuitableview

提问by Shmidt

UITableViewset to static cells.

UITableView设置为静态单元格。

Is it possible to hide some of the cells programmatically?

是否可以以编程方式隐藏某些单元格?

采纳答案by Peter Lapisu

You are looking for this solution :

您正在寻找此解决方案:

StaticDataTableViewController 2.0

静态数据表视图控制器 2.0

https://github.com/xelvenone/StaticDataTableViewController

https://github.com/xelvenone/StaticDataTableViewController

which can show/hide/reload any static cell(s) with or without animation!

它可以显示/隐藏/重新加载任何带有或不带有动画的静态单元格!

[self cell:self.outletToMyStaticCell1 setHidden:hide]; 
[self cell:self.outletToMyStaticCell2 setHidden:hide]; 
[self reloadDataAnimated:YES];

Note to always use only (reloadDataAnimated:YES/NO) (dont call [self.tableView reloadData] directly)

注意始终只使用 (reloadDataAnimated:YES/NO)(不要直接调用 [self.tableView reloadData])

This doesn't use the hacky solution with setting height to 0 and allows you to animate the change and hide whole sections

这不使用将高度设置为 0 的 hacky 解决方案,并允许您为更改设置动画并隐藏整个部分

回答by Justas

To hide static cells in UITable:

在 UITable 中隐藏静态单元格:

  1. Add this method:
  1. 添加此方法

In your UITableView controller delegate class:

在您的 UITableView 控制器委托类中:

Objective-C:

目标-C:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if(cell == self.cellYouWantToHide)
        return 0; //set the hidden cell's height to 0

    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

Swift:

迅速:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)

    if cell == self.cellYouWantToHide {
        return 0
    }

    return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

This method will get called for each cell in the UITable. Once it calls it for the cell you want to hide, we set its height to 0. We identify the target cell by creating an outlet for it:

将为 UITable 中的每个单元格调用此方法。一旦它为您想要隐藏的单元格调用它,我们将其高度设置为 0。我们通过为它创建一个出口来识别目标单元格:

  1. In the designer, create an outlet for the cell(s) you want to hide.The outlet for one such cell is called "cellYouWantToHide" above.
  2. Check "Clip Subviews" in the IB for the cells you want to hide.The cells you are hiding need to have ClipToBounds = YES. Otherwise the text will pile up in the UITableView.
  1. 在设计器中,为要隐藏的单元格创建一个出口。一个这样的单元格的出口在上面称为“cellYouWantToHide”。
  2. 在 IB 中选中“剪辑子视图”以查找要隐藏的单元格。您隐藏的单元格需要具有 ClipToBounds = YES。否则文字会堆积在 UITableView 中。

回答by Mohamed Saleh

The best way is as described in the following blog http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/

最好的方法如以下博客中所述 http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/

Design your static table view as normal in interface builder – complete with all potentially hidden cells. But there is one thing you must do for every potential cell that you want to hide – check the “Clip subviews” property of the cell, otherwise the content of the cell doesn't disappear when you try and hide it (by shrinking it's height – more later).

SO – you have a switch in a cell and the switch is supposed to hide and show some static cells. Hook it up to an IBAction and in there do this:

[self.tableView beginUpdates];
[self.tableView endUpdates];

That gives you nice animations for the cells appearing and disappearing. Now implement the following table view delegate method:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
    // Show or hide cell
        if (self.mySwitch.on) {
            return 44; // Show the cell - adjust the height as you need
        } else {
            return 0; // Hide the cell
        }
   }
   return 44;
}

And that's it. Flip the switch and the cell hides and reappears with a nice, smooth animation.

在界面构建器中像往常一样设计静态表视图 - 完成所有可能隐藏的单元格。但是对于要隐藏的每个潜在单元格,您必须做一件事 - 检查单元格的“剪辑子视图”属性,否则当您尝试隐藏它时单元格的内容不会消失(通过缩小它的高度– 稍后再说)。

所以 - 你在一个单元格中有一个开关,这个开关应该隐藏和显示一些静态单元格。将其连接到 IBAction 并在其中执行以下操作:

[self.tableView beginUpdates];
[self.tableView endUpdates];

这为细胞出现和消失提供了很好的动画。现在实现以下表视图委托方法:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
    // Show or hide cell
        if (self.mySwitch.on) {
            return 44; // Show the cell - adjust the height as you need
        } else {
            return 0; // Hide the cell
        }
   }
   return 44;
}

就是这样。翻转开关,单元格会以漂亮、流畅的动画隐藏和重新出现。

回答by henning77

My solution goes into a similar direction as Gareth, though I do some things differently.

我的解决方案与 Gareth 朝着类似的方向发展,尽管我做的事情有所不同。

Here goes:

开始:

1. Hide the cells

1.隐藏单元格

There is no way to directly hide the cells. UITableViewControlleris the data source which provides the static cells, and currently there is no way to tell it "don't provide cell x". So we have to provide our own data source, which delegates to the UITableViewControllerin order to get the static cells.

没有办法直接隐藏单元格。UITableViewController是提供静态单元格的数据源,目前无法告诉它“不提供单元格 x”。所以我们必须提供我们自己的数据源,它委托给UITableViewController以获取静态单元格。

Easiest is to subclass UITableViewController, and override all methods which need to behave differently when hiding cells.

最简单的方法是子类化UITableViewController,并覆盖隐藏单元格时需要表现不同的所有方法

In the simplest case (single section table, all cells have the same height), this would go like this:

在最简单的情况下(单节表,所有单元格具有相同的高度),这将是这样的:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    
{
    return [super tableView:tableView numberOfRowsInSection:section] - numberOfCellsHidden;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Recalculate indexPath based on hidden cells
    indexPath = [self offsetIndexPath:indexPath];

    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}

- (NSIndexPath*)offsetIndexPath:(NSIndexPath*)indexPath
{
    int offsetSection = indexPath.section; // Also offset section if you intend to hide whole sections
    int numberOfCellsHiddenAbove = ... // Calculate how many cells are hidden above the given indexPath.row
    int offsetRow = indexPath.row + numberOfCellsHiddenAbove;

    return [NSIndexPath indexPathForRow:offsetRow inSection:offsetSection];
}

If your table has multiple sections, or the cells have differing heights, you need to override more methods. The same principle applies here: You need to offset indexPath, section and row before delegating to super.

如果你的表格有多个部分,或者单元格有不同的高度,你需要覆盖更多的方法。同样的原则在这里适用:在委托给 super 之前,您需要偏移 indexPath、section 和 row。

Also keep in mind that the indexPath parameter for methods like didSelectRowAtIndexPath:will be different for the same cell, depending on state (i.e. the number of cells hidden). So it is probably a good idea to always offset any indexPath parameter and work with these values.

还要记住didSelectRowAtIndexPath:,根据状态(即隐藏的单元格数量),类似方法的 indexPath 参数对于同一单元格会有所不同。因此,始终偏移任何 indexPath 参数并使用这些值可能是一个好主意。

2. Animate the change

2. 动画变化

As Gareth already stated, you get major glitches if you animate changes using reloadSections:withRowAnimation:method.

正如 Gareth 已经说过的,如果您使用reloadSections:withRowAnimation:方法对更改进行动画处理,则会出现重大故障。

I found out that if you call reloadData:immediately afterwards, the animation is much improved (only minor glitches left). The table is displayed correctly after the animation.

我发现如果你reloadData:之后立即调用,动画会得到很大改善(只剩下小故障)。动画后表格正确显示。

So what I am doing is:

所以我正在做的是:

- (void)changeState
{
     // Change state so cells are hidden/unhidden
     ...

    // Reload all sections
    NSIndexSet* reloadSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfSectionsInTableView:tableView])];

    [tableView reloadSections:reloadSet withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView reloadData];
}

回答by Saleh Masum

  1. In the designer, create an outlet for the cell(s) you want to hide. For example you want to hide 'cellOne', so in viewDidLoad() do this
  1. 在设计器中,为要隐藏的单元格创建一个出口。例如你想隐藏“cellOne”,所以在 viewDidLoad() 中这样做

cellOneOutlet.hidden = true

cellOneOutlet.hidden = 真

now override the below method, check which cell status is hidden and return height 0 for those cell(s). This is one of many ways you can hide any cell in static tableView in swift.

现在覆盖下面的方法,检查隐藏的单元格状态并为这些单元格返回高度 0。这是您可以快速隐藏静态 tableView 中任何单元格的众多方法之一。

override func tableView(tableView: UITableView, heightForRowAtIndexPathindexPath: NSIndexPath) -> CGFloat 
{

let tableViewCell = super.tableView(tableView,cellForRowAtIndexPath: indexPath)

        if tableViewCell.hidden == true
        {
            return 0
        }
        else{
             return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
        }

}

回答by Austin

I came up with an alternative that actually hides sections and doesn't delete them. I tried @henning77's approach, but I kept running into problems when I changed the number of sections of the static UITableView. This method has worked really well for me, but I'm primarily trying to hide sections instead of rows. I am removing some rows on the fly successfully, but it is a lot messier, so I've tried to group things into sections that I need to show or hide. Here is an example of how I'm hiding sections:

我想出了一个实际上隐藏部分而不删除它们的替代方法。我尝试了@henning77 的方法,但是当我更改静态 UITableView 的部分数量时,我一直遇到问题。这种方法对我来说非常有效,但我主要是想隐藏部分而不是行。我正在成功地删除一些行,但它更混乱,所以我尝试将内容分组到我需要显示或隐藏的部分。这是我如何隐藏部分的示例:

First I declare a NSMutableArray property

首先我声明一个 NSMutableArray 属性

@property (nonatomic, strong) NSMutableArray *hiddenSections;

In the viewDidLoad (or after you have queried your data) you can add sections you want to hide to the array.

在 viewDidLoad 中(或在查询数据之后),您可以将要隐藏的部分添加到数组中。

- (void)viewDidLoad
{
    hiddenSections = [NSMutableArray new];

    if(some piece of data is empty){
        // Add index of section that should be hidden
        [self.hiddenSections addObject:[NSNumber numberWithInt:1]];
    }

    ... add as many sections to the array as needed

    [self.tableView reloadData];
}

Then implement the following the TableView delegate methods

然后实现下面的TableView委托方法

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
        return nil;
    }

    return [super tableView:tableView titleForHeaderInSection:section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
        return 0;
    }

    return [super tableView:tableView heightForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
        [cell setHidden:YES];
    }
}

Then set the header and footer height to 1 for hidden sections because you can't set the height to 0. This causes an additional 2 pixel space, but we can make up for it by adjusting the height of the next visible header.

然后将隐藏部分的页眉和页脚高度设置为1,因为您不能将高度设置为0。这会导致额外的2个像素空间,但我们可以通过调整下一个可见页眉的高度来弥补它。

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{
    CGFloat height = [super tableView:tableView heightForHeaderInSection:section];

    if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
        height = 1; // Can't be zero
    }
    else if([self tableView:tableView titleForHeaderInSection:section] == nil){ // Only adjust if title is nil
        // Adjust height for previous hidden sections
        CGFloat adjust = 0;

        for(int i = (section - 1); i >= 0; i--){
            if([self.hiddenSections containsObject:[NSNumber numberWithInt:i]]){
                adjust = adjust + 2;
            }
            else {
                break;
            }
        }

        if(adjust > 0)
        {                
            if(height == -1){
                height = self.tableView.sectionHeaderHeight;
            }

            height = height - adjust;

            if(height < 1){
                height = 1;
            }
        }
    }

    return height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section 
{   
    if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
        return 1;
    }
    return [super tableView:tableView heightForFooterInSection:section];
}

Then, if you do have specific rows to hide you can adjust the numberOfRowsInSection and which rows are returned in cellForRowAtIndexPath. In this example here I have a section that has three rows where any three could be empty and need to be removed.

然后,如果确实有要隐藏的特定行,则可以调整 numberOfRowsInSection 以及在 cellForRowAtIndexPath 中返回的行。在这个例子中,我有一个包含三行的部分,其中任何三行都可能是空的,需要删除。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = [super tableView:tableView numberOfRowsInSection:section];

    if(self.organization != nil){
        if(section == 5){ // Contact
            if([self.organization objectForKey:@"Phone"] == [NSNull null]){     
                rows--;
            }

            if([self.organization objectForKey:@"Email"] == [NSNull null]){     
                rows--;
            }

            if([self.organization objectForKey:@"City"] == [NSNull null]){     
                rows--;
            }
        }
    }

    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    return [super tableView:tableView cellForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}

Use this offsetIndexPath to calculate the indexPath for rows where you are conditionally removing rows. Not needed if you are only hiding sections

使用此 offsetIndexPath 计算有条件删除行的行的 indexPath。如果您只是隐藏部分,则不需要

- (NSIndexPath *)offsetIndexPath:(NSIndexPath*)indexPath
{
    int row = indexPath.row;

    if(self.organization != nil){
        if(indexPath.section == 5){
            // Adjust row to return based on which rows before are hidden
            if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){     
                row++;
            }
            else if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Address"] != [NSNull null]){     
                row = row + 2;
            }
            else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] != [NSNull null] && [self.organization objectForKey:@"Email"] == [NSNull null]){     
                row++;
            }
            else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){     
                row++;
            }
        }
    }

    NSIndexPath *offsetPath = [NSIndexPath indexPathForRow:row inSection:indexPath.section];

    return offsetPath;
}

There are a lot of methods to override, but what I like about this approach is that it is re-usable. Setup the hiddenSections array, add to it, and it will hide the correct sections. Hiding the rows it a little trickier, but possible. We can't just set the height of the rows we want to hide to 0 if we're using a grouped UITableView because the borders will not get drawn correctly.

有很多方法可以覆盖,但我喜欢这种方法的地方在于它是可重用的。设置 hiddenSections 数组,添加到它,它将隐藏正确的部分。隐藏行有点棘手,但可能。如果我们使用分组的 UITableView,我们不能只将要隐藏的行的高度设置为 0,因为边框将无法正确绘制。

回答by Sergey Skoblikov

Turns out, you can hide and show cells in a static UITableView - and with animation. And it is not that hard to accomplish.

事实证明,您可以在静态 UITableView 中隐藏和显示单元格 - 并带有动画。而且这并不难实现。

Demo project

演示项目

Demo project video

演示项目视频

The gist:

要点:

  1. Use tableView:heightForRowAtIndexPath:to specify cell heights dynamically based on some state.
  2. When the state changes animate cells showing/hiding by calling tableView.beginUpdates();tableView.endUpdates()
  3. Do not call tableView.cellForRowAtIndexPath:inside tableView:heightForRowAtIndexPath:. Use cached indexPaths to differentiate the cells.
  4. Do not hide cells. Set "Clip Subviews" property in Xcode instead.
  5. Use Custom cells (not Plain etc) to get a nice hiding animation. Also, handle Auto Layout correctly for the case when cell height == 0.
  1. Use tableView:heightForRowAtIndexPath:根据某些状态动态指定单元格高度。
  2. 当状态改变动画单元格显示/隐藏时调用 tableView.beginUpdates();tableView.endUpdates()
  3. 不要tableView.cellForRowAtIndexPath:在里面打电话tableView:heightForRowAtIndexPath:。使用缓存的 indexPaths 来区分单元格。
  4. 不要隐藏单元格。改为在 Xcode 中设置“剪辑子视图”属性。
  5. 使用自定义单元格(不是普通单元格等)来获得漂亮的隐藏动画。此外,对于单元格高度 == 0 的情况,正确处理自动布局。

More info in my blog (Russian language)

我的博客中有更多信息(俄语)

回答by Gareth Clarke

Yes, it's definitely possible, although I am struggling with the same issue at the moment. I've managed to get the cells to hide and everything works ok, but I cannot currently make the thing animate neatly. Here is what I have found:

是的,这绝对有可能,尽管我目前正在为同样的问题苦苦挣扎。我已经设法让单元格隐藏起来并且一切正常,但是我目前无法使这个东西整齐地动画化。这是我发现的:

I am hiding rows based on the state of an ON / OFF switch in the first row of the first section. If the switch is ON there is 1 row beneath it in the same section, otherwise there are 2 different rows.

我根据第一部分第一行中 ON/OFF 开关的状态隐藏行。如果开关打开,则同一部分的下方有 1 行,否则有 2 行不同。

I have a selector called when the switch is toggled, and I set a variable to indicate which state I am in. Then I call:

我在切换开关时调用了一个选择器,我设置了一个变量来指示我所处的状态。然后我调用:

[[self tableView] reloadData];

I override the tableView:willDisplayCell:forRowAtIndexPath:function and if the cell is supposed to be hidden I do this:

我覆盖了tableView:willDisplayCell:forRowAtIndexPath:函数,如果应该隐藏单元格,我会这样做:

[cell setHidden:YES];

That hides the cell and its contents, but does not remove the space it occupies.

这会隐藏单元格及其内容,但不会删除它占用的空间。

To remove the space, override the tableView:heightForRowAtIndexPath:function and return 0 for rows that should be hidden.

要删除空间,请覆盖tableView:heightForRowAtIndexPath:函数并为应该隐藏的行返回 0。

You also need to override tableView:numberOfRowsInSection:and return the number of rows in that section. You have to do something strange here so that if your table is a grouped style the rounded corners occur on the correct cells. In my static table there is the full set of cells for the section, so there is the first cell containing the option, then 1 cell for the ON state options and 2 more cells for the OFF state options, a total of 4 cells. When the option is ON, I have to return 4, this includes the hidden option so that the last option displayed has a rounded box. When the option is off, the last two options are not displayed so I return 2. This all feels clunky. Sorry if this isn't very clear, its tricky to describe. Just to illustrate the setup, this is the construction of the table section in IB:

您还需要覆盖tableView:numberOfRowsInSection:并返回该部分中的行数。您必须在这里做一些奇怪的事情,以便如果您的表格是分组样式,则圆角出现在正确的单元格上。在我的静态表中,该部分有完整的单元格集,因此第一个单元格包含选项,然后是 1 个单元格用于 ON 状态选项,另外还有 2 个单元格用于 OFF 状态选项,总共 4 个单元格。When the option is ON, I have to return 4, this includes the hidden option so that the last option displayed has a rounded box. 如果选择关闭后,则不显示最后两个选项,因此我返回2.这一切都感到笨拙。对不起,如果这不是很清楚,很难描述。只是为了说明设置,这是 IB 中 table 部分的构造:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON
  • Row 2: Displayed when option is OFF
  • Row 3: Displayed when option is OFF
  • 第 0 行:带有 ON / OFF 开关的选项
  • 第 1 行:选项为 ON 时显示
  • 第 2 行:选项关闭时显示
  • 第 3 行:选项关闭时显示

So when the option is ON the table reports two rows which are:

因此,当该选项为 ON 时,表格会报告两行,它们是:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON
  • 第 0 行:带有 ON / OFF 开关的选项
  • 第 1 行:选项为 ON 时显示

When the option is OFF the table reports four rows which are:

When the option is OFF the table reports four rows which are:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON
  • Row 2: Displayed when option is OFF
  • Row 3: Displayed when option is OFF
  • 第 0 行:带有 ON / OFF 开关的选项
  • 第 1 行:选项为 ON 时显示
  • 第 2 行:选项关闭时显示
  • 第 3 行:选项关闭时显示

This approach doesn't feel correct for several reasons, its just as far as I have got with my experimentation so far, so please let me know if you find a better way. The problems I have observed so far are:

由于多种原因,这种方法感觉不正确,就我迄今为止的实验而言,如果您找到更好的方法,请告诉我。到目前为止,我观察到的问题是:

  • It feels wrong to be telling the table the number of rows is different to what is presumably contained in the underlying data.

  • I can't seem to animate the change. I've tried using tableView:reloadSections:withRowAnimation:instead of reloadData and the results don't seem to make sense, I'm still trying to get this working. Currently what seems to happen is the tableView does not update the correct rows so one remains hidden that should be displayed and a void is left under the first row. I think this might be related to the first point about the underlying data.

  • 告诉表行数与可能包含在基础数据中的行数不同,这感觉是错误的。

  • 我似乎无法为更改设置动画。我试过使用tableView:reloadSections:withRowAnimation:而不是 reloadData,结果似乎没有意义,我仍在努力让它工作。目前似乎发生的事情是 tableView 没有更新正确的行,因此应该显示一个隐藏的行,并且在第一行下方留下一个空白。我认为这可能与关于基础数据的第一点有关。

Hopefully someone will be able to suggest alternative methods or perhaps how to extend with animation, but maybe this will get you started. My apologies for the lack of hyperlinks to functions, I put them in but they were rejected by the spam filter because I am a fairly new user.

希望有人能够建议替代方法或如何扩展动画,但也许这会让你开始。我很抱歉缺少指向函数的超链接,我将它们放入但它们被垃圾邮件过滤器拒绝,因为我是一个相当新的用户。

回答by Chris Herbst

As per Justas's answer, but for Swift 4:

根据 Justas 的回答,但对于 Swift 4:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)

    if cell == self.cellYouWantToHide {
        return 0
    }

    return super.tableView(tableView, heightForRowAt: indexPath)
}

回答by BananZ

Okay, after some trying, I have a non common answer. I am using the "isHidden" or "hidden" variable to check if this cell should be hidden.

好的,经过一些尝试,我得到了一个不常见的答案。我正在使用“isHidden”或“hidden”变量来检查是否应隐藏此单元格。

  1. create an IBOutlet to your view controller. @IBOutlet weak var myCell: UITableViewCell!

  2. Update the myCellin your custom function, example you may add it in viewDidLoad:

  1. 为您的视图控制器创建一个 IBOutlet。 @IBOutlet weak var myCell: UITableViewCell!

  2. 更新myCell自定义函数中的 ,例如您可以在 viewDidLoad 中添加它:

override func viewDidLoad() { super.viewDidLoad() self.myCell.isHidden = true }

override func viewDidLoad() { super.viewDidLoad() self.myCell.isHidden = true }

  1. in your delegate method:
  1. 在您的委托方法中:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cell = super.tableView(tableView, cellForRowAt: indexPath) guard !cell.isHidden else { return 0 } return super.tableView(tableView, heightForRowAt: indexPath) }

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cell = super.tableView(tableView, cellForRowAt: indexPath) guard !cell.isHidden else { return 0 } return super.tableView(tableView, heightForRowAt: indexPath) }

This will reduce your logic in the delegate method, and you only need to focus on your business requirement.

这将减少您在委托方法中的逻辑,您只需要专注于您的业务需求。