簡體   English   中英

無法將類型“ UIColor”的值分配為類型“ String?”

[英]Cannot assign value of type 'UIColor' to type 'String?'

我正在使用Swift構建補充工具欄。 我在此代碼中收到此錯誤:

  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!

你們知道發生了什么嗎?

該錯誤是由於以下代碼引起的:

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

您正在將UIColor分配給期望為String屬性( UILabel text屬性)。

我認為您可能正在尋找更改文本顏色的方法 ,如果需要,您需要更改以下代碼:

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

問題是您正在嘗試將UIColor分配給String 您想改為使用textColor格的textLabel上的textColor屬性,如下所示:

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

還要注意,您有一個可重用的單元標識符不匹配( "Cell"代表新創建的標識符, "cell"代表獲取它們)。


但是,這里有更大的問題。

為了消除編譯器錯誤,您真的不應該亂扔崩潰操作符! )。 當然,現在可能已經完全“安全”了(因為您進行了== 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
}

現在很容易發現是否! 是否屬於您的代碼。 沒錯。

不要相信建議您在代碼中添加額外的崩潰運算符以解決問題的人。 它只是成為更多問題的根源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM