2015-10-04 128 views
2

我的代碼在雨燕1.2工作得很好,但在斯威夫特2我收到此錯誤:錯誤:「無法將類型爲String:UIColor?的值分配給類型爲String:AnyObject的值!」

Cannot assign a value of type String: UIColor? to a value of type String: 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 
} 

回答

2

您必須添加一個!textColor

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

原因是linkTextAttributes[String : AnyObject!]而字典你想要分配的類型是[String : UIColor?]UIColorAnyObject之間的不匹配,因爲UIColor可以投射到AnyObject。問題是您提供的UIColor?是可選的。而且,您不能將可選UIColor?隱式轉換爲非可選AnyObject!。因此you必須強制展開顏色才能通過添加!UIColor?獲得UIColor

+0

感謝的人!它的工作:)。對不起,我不能投票回答你的答案,因爲我是新來的,我沒有足夠的聲望(至少需要15個)。 –

+0

你可以投我的問題,我會得到10個聲望(我認爲),我已經有5個 –

0

嘗試用這種

textView!.linkTextAttributes = [NSForegroundColorAttributeName:textView!.textColor as AnyObject!] 
相關問題