免责声明:我已经修改/正在修改我的导师从互联网上下载的一个项目。
这是我的家庭作业项目: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
}()
发布于 2019-07-10 00:46:55
您正在尝试为类型UIImage
分配UIImageView
。这是两件不同的事情。对于初学者,在将图像分配给“imageView”时,我会将其命名为“randomlyChosenFortune
”。UIImageView
是UIView的子类,即可以将其添加到视图层次结构中。UIImage
只是一张图片。它没有边框、边角半径、边框宽度等。
这意味着,当您想要将在代码中创建的UIImage实际添加到视图中时,需要通过以下方式完成:
创建一个实例,将该视图的UIImageView
image
属性设置为视图层次结构的UIImage
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
发布于 2019-07-10 00:45:17
您应该将UIImage
设置为UIImageView
的UIImage
。
您的globalElements.randomlyAssignedCookie
类型可能不是UIImage
。
如果你想设置图像类型为UIImageView
,你应该使用UIImage
类型。
只有相同类型的才能相互同步
我希望这能让情况有所不同。
好好享受吧。
https://stackoverflow.com/questions/56957153
复制相似问题