ios - 错误: "Cannot assign a value of type String: UIColor? to a value of type String: AnyObject!"

标签 ios swift2 uicolor

我的代码在 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/

相关文章:

ios - 访问系统。破坏性的红色按钮颜色

iphone - 为什么要删除 subview ?

ios - 如何使用 NSManagedObject 并取回所有数据?

ios - 更新到 Swift 2 后,Game Center 不接受我的代码

ios - DJI 无人机未连接(未调用 sdkManagerProductDidChange 委托(delegate)方法)

ios - 颜色循环产生 (null) 而不是颜色

ios - 刷新收据是否要求提供 App Store 凭据?

ios - Xcode iOS 通用应用程序图像大小

ios - Swift 2.2 泛型问题 (Xcode 7.3)

swift - 如何使用 Swift 制作随机颜色