无法在Swift中重用TableViewCells

时间:2017-11-19 00:03:03

标签: ios swift uitableview

我在swift中重用单元格有些麻烦。我希望下面的代码只针对post.altC.isEmpty实际为真的单元格执行。问题是它使所有单元格的botBtnsStackView.isHidden = true,即使altC并非全为空。我究竟做错了什么?

下面的代码来自我的PostCell文件(只是底部的configureCell代码的一部分,但是这部分出错了):

> core.js:1350 ERROR TypeError: Cannot read property 'subscribe' of
> undefined

cellForRowAt:

    if post.altC.isEmpty == true {
        botBtnsStackView.isHidden = true
    } else {
        altCLabel.text = post.altC["text"] as? String
        if let votes = post.altC["votes"]{
            self.altCVotesLbl.text = "\(votes)"
        }
    }

从PostCell文件配置Cell:

func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {

    let post = posts[indexpath.row]

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as? PostCell{
        cell.configureCell(post: post)
        return cell
    } else {
        return PostCell()
    }
}

1 个答案:

答案 0 :(得分:0)

细胞被重复使用。因此,您需要在if语句中执行的任何操作都需要在else中撤消。

所以你的剪辑需要改为:

if post.altC.isEmpty == true {
    botBtnsStackView.isHidden = true
} else {
    botBtnsStackView.isHidden = false
    altCLabel.text = post.altC["text"] as? String
    if let votes = post.altC["votes"]{
        self.altCVotesLbl.text = "\(votes)"
    }
}

您的其他人也需要更新。例如,对于" ALT A":

if post.altA.isEmpty == false {
    altALabel.text = post.altA["text"] as? String
    if let votes = post.altA["votes"]{
        self.altAVotesLbl.text = "\(votes)"
    }
} else {
    altALabel.text = ""
    self.altAVotesLbl.text = ""
    print("No data found in Alt A")
}

我在这里猜一点,但这会给你一个想法。调整此选项以满足您的实际需求。重要的是要记住,无论你为一个条件设置什么,你必须重置其他条件。

不相关但您应该将cellForRowAt重写为:

func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {
    let post = posts[indexpath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as! PostCell

    cell.configureCell(post: post)

    return cell
}

这是强制施放的情况。如果您未正确设置单元格标识符和单元格类型,则希望应用程序在开发早期崩溃。一旦正确设置并正常工作,它就不会在运行时崩溃,除非你做了什么打破它。

相关问题