2016-05-10 57 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 
} 

現在很容易發現一個!是否屬於您的代碼或沒有。它...呃沒有。

不要相信任何人建議在代碼中添加額外的碰撞運算符以解決您的問題。它只是成爲更多問題的來源。

相關問題