ios - Swift - 类型转换

标签 ios swift uitableview casting

我正在构建一个带有自定义单元格的自定义 UITableView。 每个自定义单元格都是 FormItemTableViewCell

的子类

我正在尝试填充 cellForRowAtIndexPath 中的单元格数据

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = FormItemTableViewCell();

        if(indexPath.row == 1){
            cell = tableView.dequeueReusableCellWithIdentifier(twoOptionCellIdentifier, forIndexPath: indexPath) as! TwoOptionTableViewCell
        } else {
            cell = tableView.dequeueReusableCellWithIdentifier(oneTextFieldCellIdentifier, forIndexPath: indexPath) as! OneTextFieldTableViewCell
        }



        cell.questionLabel.text = "What is the meaning of life?";

        return cell
    }

如何访问子类中的元素?

例如:TwoOptionTableViewCell 有一个 segControlOneTextFieldTableViewCell 有一个 answerTextField

最佳答案

这个问题有一些不错的答案,但它们中的大多数都有一个共同点,它们强制使用未包装的可选值,您应该尽可能避免使用它们(几乎唯一可以接受的使用它们的地方是在 IBOutlets 中)

这是我认为最好的处理方式:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCellWithIdentifier("Identifier", forIndexPath: indexPath) as? FormItemTableViewCell else {
        fatalError("Cell is not of kind FormItemTableViewCell")
    }

    switch cell {
    case let cell as TwoOptionTableViewCell where indexPath.row == 1:
        // Configure cell, which is an object of class TwoOptionTableViewCell, but only when we are in row 1
        break
    case let cell as TwoOptionTableViewCell:
        // Configure cell, which is an object of class TwoOptionTableViewCell, when the row is anything but 1
        break
    case let cell as OneTextFieldTableViewCell:
        // Configure cell, which is an object of class OneTextFieldTableViewCell
        break
    case _: print("The cell \(cell) didn't match any patterns: \(indexPath)")
    }

    cell.questionLabel.text = "What is the meaning of life?";

    return cell
}

现在让我向您介绍我认为这是最佳方式的原因。

首先,它不会强制解包任何可选值,在 switch 情况下一切都很好地解包。

它将您的单元格从表中取出(您应该始终这样做)并确保它是 FormItemTableViewCell 的子类,否则会引发 fatal error 。

通过使用 switch case,它将 cell 转换为您需要的类,同时检查它是否是您想要的索引路径。所以如果你想在共享一个类的不同行中共享一些逻辑,你可以将 indexPath.row 与多个值进行比较。如果您不使用 where 子句,它将在所有找到具有该类的单元格的地方使用相同的逻辑。

请注意,您需要添加一些逻辑来根据行获取所需的标识符。

关于ios - Swift - 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36800750/

相关文章:

ios - Splunk 薄荷 : Failed to archive dSYMs for "MyApp" to "/tmp/splunk-mint-dsyms"

iphone - 图像的全局唯一随机名称

swift - UIPageViewController:调用 viewDidLoad 时 socket 未初始化

ios - 私有(private)聊天应用程序 - Parse 和 Swift

ios - 检测第二个 tableview 单元格何时进入 View - 然后执行操作

ios - 播放音频甚至应用程序从后台删除

ios - 如何将MKMapView缩放到用户的当前位置

swift - 从 SPM 解析多个 Package.test 测试目标

ios - 以编程方式在 UIView 上添加 UITextField Swift

ios - 重新排序时无法从当前位置拖动 UITableViewCell