[英]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?]
。 UIColor
和AnyObject
之間的不匹配,因為UIColor
可以轉換為AnyObject
。 問題是UIColor?
您提供的是可選的。 並且您不能隱式轉換可選的UIColor?
到一個非可選的AnyObject!
. 因此,你必須強制解包的顏色得到UIColor
從UIColor?
通過添加一個!
.
試試這個
textView!.linkTextAttributes = [NSForegroundColorAttributeName:textView!.textColor as AnyObject!]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.