追加图像数组不追加同一图像两次



我的swift代码目标是创建一个从表视图单元格附加的图像数组。但是,如果图像重复两次,代码就会工作。现在,当附加代码时,sc.jpg在数组somepics中重复两次。只打印出一次gwen.jpg、kids.jgp和sc.jpg。我希望sc.jpg在数组中出现两次,就像它在数组somepics中一样。

var arrayThatStartsEmpty = [UIImage]()

var somePics: [UIImage] = [UIImage(named: "gwen.jpg")!, UIImage(named: "kids.jpg")!, UIImage(named: "sc.jpg")!, UIImage(named: "sc.jpg")!]

@objc func collect(){
let collect = (0..<arr.count).compactMap { (theTable.cellForRow(at: IndexPath(row: $0, section: 0)) as? customtv)?.pic }
let arrayValues2 = collect.compactMap { $0.image }
arrayThatStartsEmpty.append(contentsOf: arrayValues2)
print(arrayValues2)
}

我对您的collect()方法进行了一些更改。你可以试试

@objc func collect(){
let collect = arr.enumerated().compactMap { (index, _) in 
(theTable.cellForRow(at: IndexPath(row: index, section: 0)) as? customtv)?.pic }
let arrayValues2 = collect.compactMap { $0.image }
arrayThatStartsEmpty.append(contentsOf: arrayValues2)
print(arrayValues2)
}

最新更新