402

UITableView在我的 iPhone 应用程序中使用 a,并且我有一个属于某个组的人员列表。我希望这样当用户单击特定的人(从而选择单元格)时,单元格的高度会增加以显示几个 UI 控件来编辑该人的属性。

这可能吗?

4

21 回答 21

887

UITableView我找到了一个非常简单的解决方案,作为我正在研究的副作用......

将单元格高度存储在通常通过 报告原始高度的变量中tableView: heightForRowAtIndexPath:,然后当您想要动画高度变化时,只需更改变量的值并调用它...

[tableView beginUpdates];
[tableView endUpdates];

您会发现它不会完全重新加载,但足以让UITableView用户知道它必须重绘单元格,获取单元格的新高度值......猜猜怎么着?它为您带来变化。甜的。

我的博客上有更详细的解释和完整的代码示例... Animate UITableView Cell Height Change

于 2010-01-14T11:42:26.963 回答
64

我喜欢西蒙·李的回答。我实际上并没有尝试这种方法,但它看起来会改变列表中所有单元格的大小。我希望只改变被窃听的单元格。我有点像西蒙那样做,但只有一点点不同。这将在选中单元格时更改其外观。它确实有动画效果。只是另一种方法。

创建一个 int 来保存当前选定单元格索引的值:

int currentSelection;

然后:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = [indexPath row];
    selectedNumber = row;
    [tableView beginUpdates];
    [tableView endUpdates];
}

然后:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([indexPath row] == currentSelection) {
        return  80;
    }
    else return 40;


}

我相信您可以在 tableView:cellForRowAtIndexPath: 中进行类似的更改,以更改单元格的类型,甚至为单元格加载 xib 文件。

像这样,currentSelection 将从 0 开始。如果您不希望列表的第一个单元格(在索引 0 处)默认被选中,则需要进行调整。

于 2011-04-25T23:25:51.510 回答
22

添加属性以跟踪所选单元格

@property (nonatomic) int currentSelection;

将其设置为 (例如) 中的哨兵值viewDidLoad,以确保UITableView从“正常”位置开始

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //sentinel
    self.currentSelection = -1;
}

heightForRowAtIndexPath您可以为所选单元格设置所需的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int rowHeight;
    if ([indexPath row] == self.currentSelection) {
        rowHeight = self.newCellHeight;
    } else rowHeight = 57.0f;
    return rowHeight;
}

如果didSelectRowAtIndexPath需要,保存当前选择并保存动态高度

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        // do things with your cell here

        // set selection
        self.currentSelection = indexPath.row;
        // save height for full text label
        self.newCellHeight = cell.titleLbl.frame.size.height + cell.descriptionLbl.frame.size.height + 10;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

didDeselectRowAtIndexPath将选择索引设置回标记值并将单元格设置为正常形式

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {       
        // do things with your cell here

        // sentinel
        self.currentSelection = -1;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}
于 2013-08-05T16:02:31.380 回答
16

而不是beginUpdates()/ endUpdates(),现在推荐的调用是:

tableView.performBatchUpdates(nil, completion: nil)

Apple 说,关于 beginUpdates/endUpdates:“尽可能使用 performBatchUpdates(_:completion:) 方法而不是这个方法。”

请参阅:https ://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates

于 2018-11-19T16:47:52.377 回答
14

reloadData 不好,因为没有动画......

这是我目前正在尝试的:

NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

它几乎可以正常工作。几乎。我正在增加单元格的高度,有时在替换单元格时表格视图中会出现一些“打嗝”,好像表格视图中的某些滚动位置正在被保留,新单元格(这是第一个单元格在表中)以它的偏移量太高结束,并且滚动视图反弹以重新定位它。

于 2009-05-06T23:24:36.700 回答
11

我不知道关于连续调用 beginUpdates/endUpdates 的所有这些东西是什么,你可以使用-[UITableView reloadRowsAtIndexPaths:withAnimation:]. 这是一个示例项目

于 2014-08-02T22:52:00.997 回答
10

我解决了reloadRowsAtIndexPaths

我保存在didSelectRowAtIndexPath所选单元格的 indexPath 中并reloadRowsAtIndexPaths在最后调用(您可以发送 NSMutableArray 以获取要重新加载的元素列表)。

heightForRowAtIndexPath您可以检查 indexPath 是否在 expandIndexPath 单元格的列表中并发送高度。

您可以查看这个基本示例: https ://github.com/ferminhg/iOS-Examples/tree/master/iOS-UITableView-Cell-Height-Change/celdascambiadetam 这是一个简单的解决方案。

如果对您有帮助,我会添加一种代码

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath*)indexPath
{
    if ([indexPath isEqual:_expandIndexPath])
        return 80;

    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Celda";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    [cell.textLabel setText:@"wopwop"];

    return cell;
}

#pragma mark -
#pragma mark Tableview Delegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *modifiedRows = [NSMutableArray array];
    // Deselect cell
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE];
    _expandIndexPath = indexPath;
    [modifiedRows addObject:indexPath];

    // This will animate updating the row sizes
    [tableView reloadRowsAtIndexPaths:modifiedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
于 2014-11-14T13:20:05.123 回答
5

Swift 4 及更高版本

将以下代码添加到您的 tableview 的 didselect 行委托方法中

tableView.beginUpdates()
tableView.setNeedsLayout()
tableView.endUpdates()
于 2018-11-23T11:53:03.153 回答
3

试试这是为了扩展索引行:

@property (nonatomic) NSIndexPath *expandIndexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if ([indexPath isEqual:self.expandedIndexPath])
    return 100;

return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *modifiedRows = [NSMutableArray array];
if ([indexPath isEqual:self.expandIndexPath]) {
    [modifiedRows addObject:self.expandIndexPath];
    self.expandIndexPath = nil;
} else {
    if (self.expandedIndexPath)
        [modifiedRows addObject:self.expandIndexPath];

    self.expandIndexPath = indexPath;
    [modifiedRows addObject:indexPath];
}

// This will animate updating the row sizes
[tableView reloadRowsAtIndexPaths:modifiedRows withRowAnimation:UITableViewRowAnimationAutomatic];

// Preserve the deselection animation (if desired)
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ViewControllerCellReuseIdentifier];
    cell.textLabel.text = [NSString stringWithFormat:@"I'm cell %ld:%ld", (long)indexPath.section, (long)indexPath.row];

return cell;
}
于 2014-09-24T05:41:11.287 回答
3
BOOL flag;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    flag = !flag;
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:@[indexPath] 
                     withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES == flag ? 20 : 40;
}
于 2016-08-15T16:32:22.750 回答
2

只是给像我这样的人在自定义单元格上搜索添加“更多详细信息”的注释。

[tableView beginUpdates];
[tableView endUpdates];

做得很好,但不要忘记“裁剪”单元格视图。从界面生成器中选择您的单元格 -> 内容视图 -> 从属性检查器中选择“剪辑子视图

于 2015-03-25T20:08:15.120 回答
2

这是 Swift 3 的 Simons 答案的较短版本。还允许切换单元格的选择

var cellIsSelected: IndexPath?


  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    cellIsSelected = cellIsSelected == indexPath ? nil : indexPath
    tableView.beginUpdates()
    tableView.endUpdates()
  }


  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if cellIsSelected == indexPath {
      return 250
    }
    return 65
  }
于 2017-05-30T23:36:56.357 回答
1

是的,这是可能的。

UITableView有一个委托方法didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [UIView animateWithDuration:.6
                          delay:0
         usingSpringWithDamping:UIViewAnimationOptionBeginFromCurrentState
          initialSpringVelocity:0
                        options:UIViewAnimationOptionBeginFromCurrentState animations:^{

                            cellindex = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
                            NSArray* indexArray = [NSArray arrayWithObjects:indexPath, nil];
                            [violatedTableView beginUpdates];
                            [violatedTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
                            [violatedTableView endUpdates];
                        }
                     completion:^(BOOL finished) {
    }];
}

但是在您的情况下,如果用户滚动并选择不同的单元格,那么您需要让最后一个选定的单元格缩小和展开当前选定的单元reloadRowsAtIndexPaths:格调heightForRowAtIndexPath:用,以便相应地处理。

于 2016-08-01T11:29:15.773 回答
1

Simon Lee 的答案的 Swift 版本。

// MARK: - Variables 
  var isCcBccSelected = false // To toggle Bcc.



    // MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    // Hide the Bcc Text Field , until CC gets focused in didSelectRowAtIndexPath()
    if self.cellTypes[indexPath.row] == CellType.Bcc {
        if (isCcBccSelected) {
            return 44
        } else {
            return 0
        }
    }

    return 44.0
}

然后在 didSelectRowAtIndexPath()

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.tableView.deselectRowAtIndexPath(indexPath, animated: true)

    // To Get the Focus of CC, so that we can expand Bcc
    if self.cellTypes[indexPath.row] == CellType.Cc {

        if let cell = tableView.cellForRowAtIndexPath(indexPath) as? RecipientTableViewCell {

            if cell.tag == 1 {
                cell.recipientTypeLabel.text = "Cc:"
                cell.recipientTextField.userInteractionEnabled = true
                cell.recipientTextField.becomeFirstResponder()

                isCcBccSelected = true

                tableView.beginUpdates()
                tableView.endUpdates()
            }
        }
    }
}
于 2016-06-07T15:30:24.187 回答
0

在 iOS 7 及更高版本之后检查此方法。

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

iOS 8 对此进行了改进。我们可以将其设置为表格视图本身的属性。

于 2016-03-04T12:10:04.983 回答
0

Simon Lee 的Swift 版本的回答:

tableView.beginUpdates()
tableView.endUpdates()

请记住,您应该在BEFORE 之前 endUpdates()修改高度属性。

于 2018-02-08T14:11:55.483 回答
0

这是我的自定义UITableView子类代码,它UITextView在表格单元格处展开,无需重新加载(并且丢失键盘焦点):

- (void)textViewDidChange:(UITextView *)textView {
    CGFloat textHeight = [textView sizeThatFits:CGSizeMake(self.width, MAXFLOAT)].height;
    // Check, if text height changed
    if (self.previousTextHeight != textHeight && self.previousTextHeight > 0) {
        [self beginUpdates];

        // Calculate difference in height
        CGFloat difference = textHeight - self.previousTextHeight;

        // Update currently editing cell's height
        CGRect editingCellFrame = self.editingCell.frame;
        editingCellFrame.size.height += difference;
        self.editingCell.frame = editingCellFrame;

        // Update UITableView contentSize
        self.contentSize = CGSizeMake(self.contentSize.width, self.contentSize.height + difference);

        // Scroll to bottom if cell is at the end of the table
        if (self.editingNoteInEndOfTable) {
            self.contentOffset = CGPointMake(self.contentOffset.x, self.contentOffset.y + difference);
        } else {
            // Update all next to editing cells
            NSInteger editingCellIndex = [self.visibleCells indexOfObject:self.editingCell];
            for (NSInteger i = editingCellIndex; i < self.visibleCells.count; i++) {
                UITableViewCell *cell = self.visibleCells[i];
                CGRect cellFrame = cell.frame;
                cellFrame.origin.y += difference;
                cell.frame = cellFrame;
            }
        }
        [self endUpdates];
    }
    self.previousTextHeight = textHeight;
}
于 2015-11-10T02:14:40.437 回答
0

输入 -

tableView.beginUpdates() tableView.endUpdates() 这些函数不会调用

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}

但是,如果你这样做, tableView.reloadRows(at: [selectedIndexPath! as IndexPath], with: .none)

它将调用 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {} 这个函数。

于 2018-03-28T11:08:58.123 回答
0

我使用了@Joy 的出色答案,它与 ios 8.4 和 XCode 7.1.1 完美配合。

如果您希望使您的单元格可切换,我将 -tableViewDidSelect 更改为以下内容:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//This is the bit I changed, so that if tapped once on the cell, 
//cell is expanded. If tapped again on the same cell, 
//cell is collapsed. 
    if (self.currentSelection==indexPath.row) {
        self.currentSelection = -1;
    }else{
        self.currentSelection = indexPath.row;
    }
        // animate
        [tableView beginUpdates];
        [tableView endUpdates];

}

我希望这对你有所帮助。

于 2015-11-19T21:00:56.900 回答
-1

I just resolved this problem with a little hack:

static int s_CellHeight = 30;
static int s_CellHeightEditing = 60;

- (void)onTimer {
    cellHeight++;
    [tableView reloadData];
    if (cellHeight < s_CellHeightEditing)
        heightAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain];
}

- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        if (isInEdit) {
            return cellHeight;
        }
        cellHeight = s_CellHeight;
        return s_CellHeight;
}

When I need to expand the cell height I set isInEdit = YES and call the method [self onTimer] and it animates the cell growth until it reach the s_CellHeightEditing value :-)

于 2009-08-20T20:18:59.380 回答
-2

获取所选行的索引路径。重新加载表。在 UITableViewDelegate 的 heightForRowAtIndexPath 方法中,将所选行的高度设置为不同的高度,其他的返回正常的行高

于 2009-01-21T15:13:54.297 回答