如何在 table 视图单元格中隐藏自定义 class 标签?

How to hide a custom class label in a table view cell?

我有一个 table 视图控制器,带有一个自定义单元格和一个 CustomCell class。 VC 中的代码如下所示:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Actual", for: indexPath as IndexPath) as! CustomCell

    let mySeries = series[indexPath.row] as Series
    cell.mySeries = mySeries
    return cell
}

自定义类代码如下:

class CustomCell: UITableViewCell {

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var seasonLabel: UILabel!
@IBOutlet weak var episodeLabel: UILabel!

var mySeries: Series! {
    didSet {
        nameLabel.text = mySeries.name
        seasonLabel.text = mySeries.season
        episodeLabel.text = mySeries.episode
    }
}

到目前为止一切正常。但是我制作了单元格 editable 并且重新排序符号(三条纹)现在位于我的 episodeLabel 上。所以我想在编辑完成之前隐藏这个标签。重新排序的编辑功能如下所示:

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath:IndexPath) {

    let customCell = CustomCell()
    customCell.episodeLabel.isHidden = true

    let rowToMove = series[fromIndexPath.row]
    series.remove(at: fromIndexPath.row)
    series.insert(rowToMove, at: toIndexPath.row)
}

这是工作的部分。但是当我创建 CustomCell class (customCell) 的实例并将这一行插入到上面的函数中时,我得到一个致命错误,因为找到了 nil:

customCell.episodeLabel.isHidden = true

当我在 CustomCell class 中创建函数 hideEpisodeLabel() 并从 VC 中调用它时,行为相同。我做错了什么?

您必须在 moveRowAt func

中获取单元格实例
let customCell= tableView.cellForRowAtIndexPath(indexPath) as? SeriesCell
    customCell.episodeLabel.isHidden = true
 }

此附加方法以所需方式隐藏标签:

    override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    let customCell = tableView.cellForRow(at: indexPath) as? CustomCell
    customCell?.episodeLabel.isHidden = true
    return true
}

要恢复标签,我必须重新加载 table 视图。这可以通过覆盖 setEditing 方法来完成:

    override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if(!editing) {
        tableView.reloadData()
    }
}

现在,在 'cellForRowAt indexPath:' 方法中,我只需将标签设置为:isHidden = false。