【问题标题】:Custom TableViewCell | Swift自定义 TableViewCell |迅速
【发布时间】:2016-11-19 03:18:57
【问题描述】:

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

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

有两个按钮用于添加图像/文本。

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

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

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!

}

【问题讨论】:

    标签: ios swift uitableview cell tableviewcell


    【解决方案1】:

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

    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
    

    【讨论】:

    • 如果我为每个单元格设置一个类,是否有任何理由给它们标识符?
    • UITableView 使用字符串标识符来识别单元格(例如,用于重用)。如果你想使用UITableView,那么你必须根据它的API来使用它。
    • 好的,但问题是如何连接数组中的数据,并根据类型,使用所需的类并将其显示在数组中?
    • 因为在单元格类中我什么也没编码,只有 textview/imageview
    • 使用您的数组和索引路径查找行的内容并相应地设置单元格。谷歌UITableView 示例或查看Apple guides 如果您仍然感到困惑。
    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多