【问题标题】:How can I solve "Cannot assign value of type 'UIImageView?' to type 'UIImage?'" issue?如何解决“无法分配 'UIImageView' 类型的值?”输入'UIImage?'”问题?
【发布时间】:2019-07-09 16:41:06
【问题描述】:

免责声明:我已经修改/正在修改我的导师从互联网上下载的项目。

这是我的家庭作业项目:屏幕上的 3 个幸运饼干,用户点击“找出我的幸运”按钮,随机选择三个 cookie 之一(使用 .randomElement() 属性)。将打开一个窗口,显示该随机 cookie 图像。但是,我无法将窗口内的图像设置为 .randomElement() 属性的结果

我已经尝试将 UIImage 转换为 UIImageView,反之亦然,但现在我束手无策。

这是正在形成的随机元素的全局类

class globalElements {
    static let cookiesArray = [globalElements.numberOne,        
        globalElements.numberTwo, globalElements.numberThree]
    static let randomlyAssignedCookie = cookiesArray.randomElement()

}


//And here is where the title error shows up:


let randomlyChosenFortune: UIImageView = {
    let image = UIImageView()
    image.translatesAutoresizingMaskIntoConstraints = false
    image.clipsToBounds = true
    image.contentMode = .scaleAspectFit
    image.image = globalElements.randomlyAssignedCookie //(error: Cannot assign value of type 'UIImageView?' to type 'UIImage?')//

    return image
}()

【问题讨论】:

  • 你的 globalElements.randomlyAssignedCookie 的类型是什么?我认为这不是UIImage :) 如果要将图像设置为UIImageView,则应将UIImage 设置为imageView.image
  • 是的,你是对的,它是 UIImageView 类型的。你知道我怎么能解决这个问题吗?我束手无策,尝试了所有属性,甚至插值!
  • UIImageView 显示一个 UIImage。您已经说过您的图像是图像视图,但它可能是图像。将Let image = UIImageView() 更改为Let image = UIImage(),它可能会起作用。见Swift UIImageView reference

标签: ios swift uiimageview


【解决方案1】:

您正在尝试将UIImageView 分配给UIImage 类型。这是两个不同的东西。对于初学者,在将randomlyChosenFortune 分配给“imageView”时,我会命名为“image”。 UIImageView 是 UIView 的子类,即它可以添加到视图层次结构中。 UIImage 只是一个图像。它没有框架、角半径、边框宽度等内容。

这意味着,当您想要将在代码中创建的 UIImage 实际添加到视图中时,您需要这样做:

  1. 创建UIImageView 的实例
  2. UIImageView 的可选image 属性设置为UIImage
  3. UIImageView 添加到您的视图层次结构中

这里有一个很好的参考供您了解差异:Difference between UIImage and UIImageView

UIImage 参考:https://developer.apple.com/documentation/uikit/uiimage

UIImageView 参考:https://developer.apple.com/documentation/uikit/uiimageview

了解 UIView 子类化:https://developer.apple.com/documentation/uikit/uiview & https://medium.com/@fvaldivia/view-hierarchy-in-swift-ios-9f86a7479cb5

【讨论】:

    【解决方案2】:

    您应该将UIImage 设置为UIImageViewUIImage

    您的globalElements.randomlyAssignedCookietype 可能不是UIImage

    如果要将图像设置为UIImageView,则应使用UIImage 类型。

    只有相同的类型才能相互同步

    我希望这会有所作为。

    享受吧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多