我有一个自定义类Product定义为
class Product: NSObject {
var name: String
var priceLabel: String
var productImage: UIImage
init(name: String, priceLabel: String, productImage: UIImage) {
self.name = name
self.priceLabel = priceLabel
self.productImage = productImage
super.init()
}
}
我已经使用该自定义类创建了一个数组
let toy = [
Product(name: "Car", priceLabel: "$5.00"),
Product(name: "Train", priceLabel: "$2.50")
]
如何将 UIImage 插入到该数组中?我需要为每个玩具插入不同的图片。
提前致谢
最佳答案
有几种方法可以做到这一点,但使用您的代码,只需示例 1 即可:
// Example 1:
let toy = [
Product(name: "Car", priceLabel: "$5.00", productImage:UIImage(named: "myImage.png")!),
...
]
// Example 2:
let product1 = Product(name: "Car", priceLabel: "$5.00")
product1.productImage = UIImage(named: "myImage.png")!
let toy = [
product1,
...
]
// Example 3:
let toy = [
Product(name: "Car", priceLabel: "$5.00"),
...
]
if let prod = toy[0] {
prod.productImage = UIImage(named: "myImage.png")!
}
你只有一个 init 接受 3 个参数,所以如果你创建这样的对象:
Product(name: "Car", priceLabel: "$5.00")
它不会编译,因为你没有只接受两个参数的初始化程序。
关于ios - 在 Swift 中使用自定义类在数组中显示 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31564880/