如何更改UITableViewCell的高度?

时间:2015-09-22 13:28:01

标签: ios swift uitableview cocoa-touch delegates

我试图让UITableViewCell在点击特定单元格时显示有关特定单元格的更多内容。一旦细胞膨胀并再次敲击,细胞应缩小回原始大小。

我非常确定代理人heightForRowAtIndexPathdidSelectRowAtIndexPath必须要做些什么,但我不知道如何使用didSelectRowAtIndexPath选择特定的表格单元格行。

// Height of table cell rows
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 45
}

//On cell tap, expand
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.tableView.rowHeight = 75;
}

此外,是否可以隐藏从父单元溢出的任何内容?有点像溢出:隐藏;在CSS中。

4 个答案:

答案 0 :(得分:13)

didSelectRowAtIndexPath 中选择的tableview上声明全局变量 NSInteger 类型并存储,并在此处重新加载。检查 heightForRowAtIndexPath 中的行并在那里增加高度。 试试这样

var selectedIndex : NSInteger! = -1 //Delecre this global 

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == selectedIndex{
        selectedIndex = -1
    }else{
        selectedIndex = indexPath.row
    }
    tableView.reloadData()
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == selectedIndex
    {
        return 75
    }else{
        return 45
    }
}

答案 1 :(得分:5)

您需要做的是在didSelectRow方法中保存所选Cell的索引。并且还必须在表视图上开始/结束更新。这将重新加载tableview的某些部分。并将调用heightForRow方法。在该方法中,您可以检查是否选择了一行,然后返回expandedHeight,否则返回正常高度

行高:

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

    if self.selectedSortingRow == indexPath.row {
        return ExpandedRowHeight
    }
    else{
        return normalHeight
    }
}

在didSelect Row中:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    self.tableView.beginUpdates()
    selectedSortingRow = (int) indexPath.row        
    self.tableView.endUpdates()
}

答案 2 :(得分:2)

快速回答4条带有建议的评论。无需创建新变量,tableView拥有selectedRow indexPath的值。

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if self.tableView.indexPathForSelectedRow?.row == indexPath.row {
        return 75;
    } else {
    return 45;
    }
}

答案 3 :(得分:1)

Swift 4.动画大小调整,具有多个选择。基于Ryderpro的答案。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if let selectedRows = tableView.indexPathsForSelectedRows, selectedRows.contains(indexPath) {
        return 75
    } else {
        return 45
    }
}
相关问题