ios - 如何使用 if 语句将一种类型的变量设置为特定类型的自定义 tableCell?

标签 ios swift uitableview protocols

我有三种不同类型的自定义 UITableCell。我有一个 if 语句来设置它们:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {                
    if somePosts[indexPath.row].typeOfPost == .linkPost {
        let cell: LinkTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "linkTableViewCell") as! LinkTableViewCell

    } else if somePosts[indexPath.row].typeOfPost == .picturePost {
        let cell: PictureTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "pictureTableViewCell") as! PictureTableViewCell

    } else if somePosts[indexPath.row].typeOfPost == .textPost {
        let cell: TextTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "textTableViewCell") as! TextTableViewCell


    } else {
        print("Type of post is not link, picture, or text")
    }
}

每个自定义单元格都有类似的标签,例如标题和时间。我想使用同一行代码设置这些标签,例如:

cell.titleLabel.text = "Some title here"

但是,在这个例子中,我收到一条错误消息,说我正在使用一个未解析的标识符“cell”,这显然是因为我的变量是非全局声明的。有没有办法解决这个问题,因为 swift 是强类型的?谢谢!

最佳答案

制定一个您的 TableViewCell 类扩展的协议(protocol),并将 cell 存储为该类型的变量。

protocol MyTableViewCell {
    var titleLabel: UILabel { get }
    // ...
}

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

    let identifier: String

    switch somePosts[indexPath.row].typeOfPost {
        case .linkPost: identifier = "linkTableViewCell"
        case .picturePost: identifier = "pictureTableViewCell"
        case .textPost: identifier = "textTableViewCell"
        default: fatalError("Type of post is not link, picture, or text")
    }

    guard let cell = self.tableView.dequeueReusableCell(withIdentifier: identifier) as? MyTableViewCell else {
        fatalError("Cell isn't castable to MyTableViewCell")
    }

    cell.titleLabel.text = "Some title here" 
    // ...
}

关于ios - 如何使用 if 语句将一种类型的变量设置为特定类型的自定义 tableCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640806/

相关文章:

ios - 将 UISearchController 连接到 UISearchBar,而不将搜索栏嵌入到表格 View 或导航栏中

ios - Dropbox - 应用程序文件夹已删除 - 出现 NSURLErrorRequestBodyStreamExhausted 错误 - iOS

ios - 使用 SwiftUI 从结构中的完成变量调用方法

ios - 根据 UIPicker 位置动态调整 UILabel x 值?

ios - 按下按钮时如何更改角标(Badge)编号?

ios - 如何在 navigationBar (UITableView) swift 下添加 SearchController.searchBar

ios - 如何让 "View All"按钮通过 segue 到下一个 ViewController 显示数据?

ios - 避免在 Swift 中将重复的图像上传文件上传到 Parse.com

objective-c - 在 Swift 中使用 Obj-C 类扩展?

c++ - 尝试从 Swift 调用 C++ 代码时出现链接器错误