在Swift中使用自定义类在数组中显示UIImage

时间:2015-07-22 13:41:25

标签: ios arrays swift uiimage swift-array

我将自定义类产品定义为

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插入该数组?我需要为每个玩具插入不同的图片。

提前致谢

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到,但只需使用您的代码示例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")

它不会编译,因为你没有只接受两个参数的初始化器。

答案 1 :(得分:0)

试试这个:

$('input[name=mon]').on('change', function() {
    $('select[name=firstTime], select[name=secondTime]').prop('disabled', this.value != 'time');
});

旁注:如果您想使初始化程序更加动态,请使用默认参数。

let newArray = toy.map{Product(name: $0.name, priceLabel: $0.priceLabel, productImage:UIImage(named: "myImage.png")!)}
相关问题