簡體   English   中英

錯誤:“無法將 String: UIColor 類型的值分配給 String: AnyObject 類型的值!”

[英]Error: "Cannot assign a value of type String: UIColor? to a value of type String: AnyObject!"

我的代碼在 Swift 1.2 中運行良好,但在 Swift 2 中我收到此錯誤:

無法分配字符串類型的值:UIColor? 到字符串類型的值:AnyObject!

我的代碼是:

 override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell

    let message = messages[indexPath.row]

    if message.senderId == self.senderId {
        cell.textView!.textColor = UIColor.blackColor()
    } else {
        cell.textView!.textColor = UIColor.whiteColor()
    }

    // Error in the following line 
    cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:cell.textView!.textColor]

    return cell
}

你必須添加一個! textColor

cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:cell.textView!.textColor!]

原因是linkTextAttributes[String : AnyObject!]而您要分配的字典是[String : UIColor?] UIColorAnyObject之間的不匹配,因為UIColor可以轉換為AnyObject 問題是UIColor? 您提供的是可選的。 並且您不能隱式轉換可選的UIColor? 到一個非可選的AnyObject! . 因此,必須強制解包的顏色得到UIColorUIColor? 通過添加一個! .

試試這個

textView!.linkTextAttributes = [NSForegroundColorAttributeName:textView!.textColor as AnyObject!]

暫無
暫無

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

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