自定义 TableViewCell | Swift

Custom TableViewCell | Swift

我正在尝试向 table 添加不同的内容,例如 images/text。 我为这两种类型创建了 2 个自定义 tableViewCells。我有主数组,所有内容都将保存在其中(图像编码为 base64,因为存储在 JSON 中)。

var content = [String]()
var imgCell: ImageTableViewCell = ImageTableViewCell()
var txtCell: TextTableViewCell = TextTableViewCell()

有两个用于添加的按钮 images/text。

@IBAction func textAddButton(sender: AnyObject) {
    self.content.append("text")
    self.articleTableView.reloadData()
}

在更新 table 时,我无法理解如何将数组数据与自定义单元格连接并显示。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    if content[indexPath.row] == "text" {
        return txtCell
    }
    else {
        return imgCell
    }
    return UITableViewCell()
}

这是自定义单元格。

class TextTableViewCell: UITableViewCell {

    @IBOutlet weak var textArticle: UITextView!

}

你永远不会像那样初始化单元格。在 cellForRowAtIndexPath 中调用 dequeueReusableCellWithIdentifier 并根据 indexPath 相应地设置单元格。如果您在故事板文件中创建了单元格,请确保在故事板中设置它们的标识符。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = tableView. dequeueReusableCellWithIdentifier(identifierForIndexPath(indexPath), forIndexPath:indexPath)
    // set up cell accordingly
}

func identifierForIndexPath(indexPath:NSIndexPath) -> String {
    // for example: (you can set this up according to your needs)
    if (indexPath.row == 0) {
        return "ImageCell" // these must match your identifiers in your storyboard
    }
    return "TextCell"
}

或者,您可以在 cellForRowAtIndexPath 中为每种细胞类型设置单独的块,然后您将得到如下内容:

let cell = tableView.dequeueReusableCellWithIdentifier("TextCell", forIndexPath:indexPath) as! TextTableViewCell