我的代码在 Swift 1.2 中运行良好,但在 Swift 2 中我收到此错误:
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
}
最佳答案
您必须添加 !
textColor
之后:
cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:cell.textView!.textColor!]
原因是linkTextAttributes
类型为[String : AnyObject!]
而您要分配的字典类型为 [String : UIColor?]
。 UIColor
之间的不匹配和AnyObject
因为UIColor
可以转换为 AnyObject
。问题是UIColor?
您提供的是可选的。并且您不能隐式转换可选的 UIColor?
为非可选 AnyObject!
。因此您必须强制展开颜色才能获得 UIColor
来自UIColor?
通过添加 !
.
关于ios - 错误: "Cannot assign a value of type String: UIColor? to a value of type String: AnyObject!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32932022/