使用自调整大小的单元格后,reloadData 不再起作用

After using self sizing cells reloadData doesn't work anymore

我有一个带有自定义单元格的 UITableView。单元格中有一个按钮、一个标签和一个隐藏标签。我希望隐藏标签在单击按钮后可见。但是当我使用自动调整大小的单元格时,我无法在将隐藏标签设置为可见后重新加载我的 tableView。

自动调整单元格与 viewDidLoad() 函数中的这两行代码一起工作得很好。

self.tableView.estimatedRowHeight = 68.0
self.tableView.rowHeight = UITableViewAutomaticDimension

这是我的 ViewController class:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()

    //Self sizing cells
    self.tableView.estimatedRowHeight = 68.0
    self.tableView.rowHeight = UITableViewAutomaticDimension
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
    cell.leftLabel.text = "Left Label"
    cell.centerLabel.text = "I am the center label and I need a little more words because I am supposed to be a wrap content. I hope this is enough"
    cell.button.tag = indexPath.row
    cell.button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

func buttonAction(sender: AnyObject) {
    var button: UIButton = sender as! UIButton
    let indexPath: NSIndexPath = NSIndexPath(forRow: button.tag, inSection: 0)
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
    cell.centerLabel.hidden = false
    self.tableView.reloadData()
}
}

只要我打电话

self.tableView.estimatedRowHeight = 68.0

buttonAction 函数中的 reloadData 调用不再起作用。

谁能帮我解决这个问题? 谢谢!

reloadData后,你的cell.centerLabel.hidden也失效了。 由于您不更改 cellForXXX 中的 centerLable.hidden,centerLable-hidden 单元格将位于 table.

中的任何位置

试试这个。您使用 cellForRowAtIndexPath 来获取 tableView 中该位置的单元格,而不是 dequeueReusableCellWithIdentifier

func buttonAction(sender: UIButton) {
    var indexPath:NSIndexPath = NSIndexPath(forRow:sender.tag, inSection: 0)
    var cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell
    cell.centerLabel.hidden = false
}

然后如果你想在重复使用单元格时隐藏 centerLabel,请在你的 CustomCell 中添加此方法 class

override func prepareForReuse() {
    self.centerLabel.hidden = true
}