【问题标题】:UITableView: How to change cell height dynamically when a button is clicked in it?UITableView:单击按钮时如何动态更改单元格高度?
【发布时间】:2015-04-10 15:54:01
【问题描述】:

我有一个 UITableView,其中每个单元格都有一个按钮。
单击按钮时,单元格的高度将发生变化。
当然,整个tableview的高度会根据它来改变。
在长时间冲浪时我找不到路。 实现这一目标的优雅解决方案是什么?

【问题讨论】:

    标签: ios uitableview autolayout layoutsubviews


    【解决方案1】:

    (请参阅 this 答案。感谢 Tapas Pal 编写原始答案。我只是将其更改为更适合您的问题。)

    您将需要一个BOOL 变量来告诉单元格它的高度应该与其他单元格不同。您还需要一个数字(这里,我将使用NSInteger)变量,以便您可以增加右侧单元格的高度。

    BOOL shouldCellBeExpanded = NO;
    NSInteger indexOfExpandedCell = -1;
    

    然后,在您的 -tableView:cellForRowAtIndexPath: 方法中,将以下内容添加到您设计单元格的位置。您将按钮标记设置为与其单元格的行相同,以便您知道要展开哪个单元格。此外,如果您需要向单元格添加任何元素,可以在if 语句中进行。

    [[cell aButton] setTag:[indexPath row]];
    
    if(shouldCellBeExpanded && [indexPath row] == indexOfExpandedCell)
    {
       // design your read more label here
    }
    

    移动到按钮的IBAction。点击按钮时,UITableView 将重新加载按钮所在的单元格。 注意:如果您在 UITableView 中使用多个部分,则需要添加另一个数字变量来解决此问题。如果您需要帮助,请发表评论。

    -(IBAction) aButtonTapped:(id)sender
    {
        UIButton *aButton = (UIButton *)sender;
        indexOfExpandedCell = [aButton tag];
        shouldCellBeExpanded = YES;
    
        [[self tableView] beginUpdates];
        [[self tableView] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem: indexOfExpandedCell inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
        [[self tableView] endUpdates];
    }
    

    最后,在-tableView:heightForRowAtIndexPath: 方法中:

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if(shouldCellBeExpanded && [indexPath row] == indexOfExpandedCell)
            return 200.0f; //Your desired height for the expanded cell
        else
            return 100.0f; //The other cells' height
    }
    

    它的作用是检查一个单元格是否应该被扩展,如果是,那么该单元格是否是当前被要求提供高度值的那个单元格。如果是,则返回值是展开后的高度。如果没有,请使用原始版本。

    【讨论】:

      【解决方案2】:

      调用函数- reloadRowsAtIndexPaths:withRowAnimation:。实现函数UITableViewDelegate函数- tableView:heightForRowAtIndexPath:并返回新的高度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多