gpt4 book ai didi

ios - 如何解决 "Cannot assign value of type ' UIImageView ?' to type ' UIImage ?'"问题?

转载 作者:行者123 更新时间:2023-11-28 11:30:24 32 4
gpt4 key购买 nike

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

这是我的作业项目:屏幕上有 3 个幸运 cookies ,用户点击“找出我的财富”按钮,随机选择三个 cookies 之一(使用 .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
}()

最佳答案

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

这意味着,当您想要将您在代码中创建的 UIImage 实际添加到您的 View 时,您需要通过以下方式进行:

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

这是一个很好的引用,供您了解差异: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

关于ios - 如何解决 "Cannot assign value of type ' UIImageView ?' to type ' UIImage ?'"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56957153/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com