单击时如何更改单个单元格的高度?

Thi*_*ago 9 uitableview ios swift xcode6 ios8

单击时,我必须调整tableView的单行大小.我怎么能这样做?有人可以帮帮我吗?

我的视图控制器类:

class DayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var daysWorkPointTable: UITableView

    override func viewDidLoad() {
        super.viewDidLoad()

        var nipName = UINib(nibName: "daysWorkPointsCell", bundle: nil)

        self.daysWorkPointTable.registerNib(nipName, forCellReuseIdentifier: "daysWorkCell")
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath) -> CGFloat {
        return 75
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell = tableView.dequeueReusableCellWithIdentifier("daysWorkCell", forIndexPath: indexPath) as daysWorkPointsCell

        return cell
    }

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Kai*_*rdt 38

首先,您必须跟踪属性中当前所选单元格的indexPath:

var selectedCellIndexPath: NSIndexPath?
Run Code Online (Sandbox Code Playgroud)

它应该是可选的,因为您可以不选择单元格.接下来,我们可以为选定状态和未选择状态声明高度(将值更改为您想要的任何值):

let selectedCellHeight: CGFloat = 88.0
let unselectedCellHeight: CGFloat = 44.0
Run Code Online (Sandbox Code Playgroud)

现在你必须实现tableView(_:, heightForRowAtIndexPath:):

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if selectedCellIndexPath == indexPath {
        return selectedCellHeight
    }
    return unselectedCellHeight
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的tableView(_:, didSelectRowAtIndexPath:)方法中,您必须检查选定的行或已点击未选择的行:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath {
        selectedCellIndexPath = nil
    } else {
        selectedCellIndexPath = indexPath
    }

    tableView.beginUpdates()
    tableView.endUpdates()

    if selectedCellIndexPath != nil {
        // This ensures, that the cell is fully visible once expanded
        tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: true)
    }
}
Run Code Online (Sandbox Code Playgroud)

beginUpdates()endUpdates()电话是给你一个动画的高度变化.

如果要更改高度变化动画的持续时间,可以在动画块中包装beginUpdates()endUpdates()调用UIView.animationWithDuration(...)并将其设置为您想要的任何值.

您可以查看此示例项目,该项目演示了此代码的实际运行情况.