【问题标题】:Swift: Is it possible to use a variable for a custom class name?Swift:是否可以为自定义类名使用变量?
【发布时间】:2015-08-13 21:50:08
【问题描述】:

我正在尝试将 CoreData 变量用于我的大部分应用程序代码,但无法将它们用于自定义类的名称。这是我的代码示例:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CREWWorkCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellName) as! CREWWorkCell

我想为 CREWWorkCell 使用一个字符串。这可能吗?

【问题讨论】:

    标签: swift subclass


    【解决方案1】:

    UITableViewController 没有返回您可以覆盖的CREWWorkCell 的函数。使用默认的 UITableViewCell 作为返回值,自定义单元格一切正常。

    在您的 UITableViewController 类中使用以下函数:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Note that the return value is UITableViewCell and not CREWWorkCell
    
            //get the class name from the database and put it in a variable called myClassName. Then 
    
            if myClassName == "CREWWorkCell" {
                let cell : CREWWorkCell = tableView.dequeueReusableCellWithIdentifier("cell identifier 1", forIndexPath: indexPath) as! CREWWorkCell //of course you should cast to your custom class to be able to use it
                return cell
            } else if myClassName == "AnotherCellClass" {
                let cell : AnotherCellClass = tableView.dequeueReusableCellWithIdentifier("cell identifier 2", forIndexPath: indexPath) as! AnotherCellClass
                return cell
            }
    
            //do the same if you have other custom classes etc...
    
            return UITableViewCell()
        }
    

    使用 Swift 你不能转换成动态类型(看看here)。因此,您不能将类型转换为您放入变量中的类型,例如:

    var myClassName = CREWWorkCell.self
    

    var myClassName = CREWWorkCell().dynamicType
    

    因为myClassName 将在运行时进行评估,换句话说,它是一个动态类型。但是转换操作符期望它的右手边是一个静态类型,这是一种已知的类型,不需要在运行时进行评估。此功能允许 Swift 强制执行类型安全。

    我建议您以更简单的方式重新考虑创建自定义单元格的方式。

    【讨论】:

    • 因为我需要为单元格使用自定义类,所以我不知道该怎么做。
    • CREWWorkCell 已经是 UITableViewCell 的子类。它工作得很好
    • 如果我有多个子类,我该如何指定使用哪一个?每个单元格中的对象都在其中指定。
    • 你必须依靠indexPath.row来设置类
    • 我还是不明白......如果你能提供一个例子,我将不胜感激。
    猜你喜欢
    • 2012-12-20
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多