当其中的文本字段开始编辑时增加单元格的高度

Increase height of a cell when textfield in it begins editing

我有一个 tableview,其中一个单元格包含一个 textfield 和一个 button。我只想在 textfield 激活时显示带有 button 的区域。

因此,那时我想提供一个不同的 height,以便 textfield 仅可见,当 textfield 激活时,我想增加 height of the tableviewcell显示 button。请帮忙。

我的手机是这样的

当未选择文本字段时,我希望它显示为:

选择文本字段后,我希望它显示如下:

它与 "Using Auto Layout in UITableView for dynamic cell layouts & variable row heights" 无关,因为我想根据所选的文本字段确定高度。

所以基本上你需要更新特定的单元格并增加它的高度。为此,您需要实施 UITextFieldDelegate 方法以确保在文本字段即将进入编辑模式时收到通知。

您还需要维护当前单元格的 indexPath 以增加特定单元格的高度。

@property(nonatomic, strong) NSIndexPath *selectedIndexPath;

将其初始值设为nil

实现委托方法

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (UITableViewCell*)textField.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if( indexPath != nil) //Returns nil if cell is not visible
    {
        if( self.selectedIndexPath != nil )
        {
            //We need to reload two cells -  one to hide UIButton of current cell, make visible the new UIButton for which textfield is being currently edited
            NSIndexPath *previousIndexPath = self.selectedIndexPath;
            self.selectedIndexPath = indexPath;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath, previousIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
        else
        {
            //Reload the cell to show the button
            self.selectedIndexPath = indexPath;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

重新加载单元格后,确保使用 UITableViewDelegate 方法更新高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( self.selectedIndexPath && [indexPath compare:self.selectedIndexPath] == NSOrderedSame)
    {
        return kHeightWithButton; //assuming its some constant defined in the code
    }
    return kHeightWithoutButton;
}

另外,根据您处理 UITableViewCell 约束的方式,您可能需要调用单元格的 updateConstraints 方法。示例代码如 be

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell; //Assuming the you have some custom class to handle cell
    cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];

    if( cell == nil )
    {
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"myCell"];
        //... code for initialization
        cell.textField.delegate = self; //set the delegate to self so that we get delegate methods
    }

    if( self.selectedIndexPath && [indexPath compare:self.selectedIndexPath] == NSOrderedSame)
    {
        cell.button.hidden = NO;
    }
    else
    {
        cell.button.hidden = YES;
    }
    [cell updateConstraints];//update constraint to adjust the UIButton's visibility and constraints

    //... other code if any

    return cell;
}

希望对您有所帮助!