【问题标题】:Unwrapping Optionals for UITableViewCell展开 UITableViewCell 的选项
【发布时间】:2015-10-23 02:08:33
【问题描述】:

我有以下代码。我正在使用所有可能的 Xcode 建议以及关于 SO 等的各种来源,但我似乎无法纠正可选问题:

var cell =
        tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell?

        if (cell == nil)
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:identifier as String)
            cell.backgroundColor = UIColor.clearColor()
// ERROR HERE 
        }

        cell.textLabel?.text = dataArray.objectAtIndex(indexPath.row).valueForKey("category_name") as! String
        // ERROR HERE

        var str = String(format: "%@%@%@",kServerURl,"/upload/",dataArray.objectAtIndex(indexPath.row).valueForKey("category_image") as! String)

        cell?.imageView?.image =  UIImage(data: NSData(contentsOfURL: NSURL(string:str)!)!)
// ERROR HERE

        return cell
//ERROR HERE

错误:

可选类型 UITABLEVIEWCELL 的价值未展开您是否打算使用!还是?

不管我用!或者 ?我得到同样的错误,在某些情况下,如果两个错误会解决!被添加层单元格!!。

【问题讨论】:

    标签: ios swift2 optional


    【解决方案1】:

    问题是你在这里有一个双重可选:

    var cell =
        tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell?
    

    as? 表示转换可能会失败,因此它将您要转换的值包装在一个可选项中。您正在投射的那个值也是一个可选的 (String?)。因此,如果您在调试器中查看单元格的值,您会看到类似以下内容:

    Optional(Optional(<UITableViewCell:0x14f60bb10

    您可以通过以下方式显式解包:

    cell!!(两个感叹号),但这有点脏。相反,您只需要像这样的演员之一:

    var cell =
        tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell
    

    请注意,我删除了最后一个问号。然后你可以这样做:

    cell!.backgroundColor = UIColor.clearColor()
    

    最后一个选择是一开始就用感叹号强行解开它:

    tableview!.dequeueReusableCellWithIdentifier(identifier as String) as! UITableViewCell
    

    那么你只需要:

    cell.backgroundColor = UIColor.clearColor()
    

    【讨论】:

      【解决方案2】:

      单元格变量是 UITableViewCell? 类型的可选变量,因此您必须在使用它之前对其进行解包。您可能应该阅读the documentation on Optional Types 以熟悉它们的使用。像这样的行:

      cell.backgroundColor = UIColor.clearColor()
      

      应该是:

      cell!.backgroundColor = UIColor.clearColor()
      

      或:

      if let someCell = cell {
          someCell.backgroundColor = UIColor.clearColor()
      }
      

      在您知道实例不是nil 的情况下,您将使用第一种展开,例如直接在您的nil 检查 if 语句之后。如果您不确定它不是nil,则可以使用第二种展开方式。

      【讨论】:

      • 嗨,如果添加单元格!.backgroundColor = UIColor.clearColor() 我仍然得到同样的错误。如果我添加(当 Xcode 提示时) cell!!.backgroundColor = UIColor.clearColor() 它可以工作,这可能吗 - cell!!.back..
      • 将初始分配更改为此,现在可以了:var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier as String) as UITableViewCell!;
      • 你能把 as UITableViewCell 去掉吗!完全的一部分?问题是您正在获取已经是 UITableViewCell 的出队函数的结果?类型,然后您正在执行可选转换(使用 as?UITableViewCell?),这使您最终得到一个双可选类型。
      猜你喜欢
      • 2018-12-11
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      相关资源
      最近更新 更多