2016-05-10 84 views
0

我正在用Swift构建一个补充工具栏。 我得到这个错误在此代码:无法指定'UIColor'类型的值来键入'String?'

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell 

    if cell == nil{ 
     cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") 

     cell!.backgroundColor = UIColor.clearColor() 
     cell!.textLabel!.text = UIColor.darkTextColor() 
    } 

    // Configure the cell... 

    return cell 
} 

所以有确实有人这个平台,有同样的问题上。在解决方案,他们说,我要补充的背后UIColor.darkTextColor()一个!,但如果我这样做还有另外一个错误,我不得不删除!

的错误是在该行:

细胞.textLabel!

你们知道发生了什么事吗?

+1

错误信息是什么? –

+0

@JeffPuckettII在标题中? – Hamish

回答

1

的错误是由于此代码:

cell!.textLabel!.text = UIColor.darkTextColor() 

您到期望成为String(的UILabeltext属性)的属性分配UIColor

我想你可能正在改变text color,如果是的话,你需要改变这样的代码:

cell!.textLabel!.textColor = UIColor.darkTextColor() 
+0

我是Xcode的新手,所以我应该写什么呢? –

+0

答案的最后一行是你应该写的内容 – dan

+0

非常感谢! –

0

的问题是你想一个UIColor分配给String。你想用对细胞的textLabeltextColor属性来代替,就像这样:

cell.textLabel?.textColor = UIColor.darkTextColor() 

另外请注意,您有一个可重复使用的小区标识不匹配("Cell"为新创建的,"cell"用于获取它们)。


但是,这里有更大的问题。

你真的不应该在crash operators!)乱丢垃圾以清除编译器错误。当然,现在它可能是完全'安全的'(就像你做一个== nil检查) - 但它只是鼓励他们将来在他们真正不应该使用的地方使用它们。它们对未来的代码重构也可能非常危险。

我建议您重新编写代码以利用nil-coalescing运算符(??)。您可以使用它来尝试获取可重用的单元格。如果失败了,那么你可以用新创建的替代。您也可以使用自动执行的关闭({...}())来执行一些常见的单元设置。

例如:

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

    // attempt to get a reusable cell – create one otherwise 
    let cell = tableView.dequeueReusableCellWithIdentifier("foo") ?? { 

     // create new cell 
     let cell = UITableViewCell(style: .Default, reuseIdentifier: "foo") 

     // do setup for common properties 
     cell.backgroundColor = UIColor.redColor() 
     cell.selectionStyle = .None 

     // assign the newly created cell to the cell property in the parent scope 
     return cell 
    }() 

    // do setup for individual cells 
    if indexPath.row % 2 == 0 { 
     cell.textLabel?.text = "foo" 
     cell.textLabel?.textColor = UIColor.blueColor() 
    } else { 
     cell.textLabel?.text = "bar" 
     cell.textLabel?.textColor = UIColor.greenColor() 
    } 

    return cell 
} 

现在很容易发现一个!是否属于您的代码或没有。它...呃没有。

不要相信任何人建议在代码中添加额外的碰撞运算符以解决您的问题。它只是成为更多问题的来源。

相关问题