I have array with selected images from media library. And I need to delete selected image by clicking on button.
ScrollView(.horizontal) {
HStack(spacing: 5) {
ForEach(self.selectedMedia, id:\.self) { index in
ZStack {
Image(uiImage: index.image)
.resizable()
.scaledToFit()
.frame(width: UIScreen.main.bounds.width * 0.5)
Button(action: {
removeItem(at: index)
}, label: {
Image(systemName: "trash")
.padding(5)
.foregroundColor(Color.red)
.background(Color.white)
})
}
}
}
}
func removeItem(at index: Int) {
self.selectedMedia.remove(at: index)
}
But can't build project, because have an error:
Cannot convert value of type 'SelectedMedia' to expected argument type 'Int'
SelectedMedia
:
struct SelectedMedia: Hashable {
var asset: PHAsset
var image: UIImage
}
If I print current element in array print(index)
, will get in console:
SelectedMedia(asset: <PHAsset: 0x149313570> ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED/L0/001 mediaType=1/0, sourceType=1, (3000x2002), creationDate=2012-08-08 21:55:30 +0000, location=1, hidden=0, favorite=0, adjusted=0 , image: <UIImage:0x6000004c4360 anonymous {3000, 2002}>)
How to fix error and delete image?
There are many ways you can use this.
Approach 1: Use indices
and then get an object from the index.
ForEach(selectedMedia.indices, id:\.self) { index in // <-- Here
let obj = selectedMedia[index] // <-- Here
ZStack {
Image(uiImage: obj.image) // <-- Here
.resizable()
.scaledToFit()
.frame(width: UIScreen.main.bounds.width * 0.5)
Button(action: {
removeItem(at: index) // <-- Here
}, label: {
Image(systemName: "trash")
.padding(5)
.foregroundColor(Color.red)
.background(Color.white)
})
}
}
Approach 2: Use enumerated()
it will give you both item object and offset.
ForEach(Array(selectedMedia.enumerated()), id:\.offset) { index, obj in // <-- Here
ZStack {
Image(uiImage: obj.image) // <-- Here
.resizable()
.scaledToFit()
.frame(width: UIScreen.main.bounds.width * 0.5)
Button(action: {
removeItem(at: index) // <-- Here
}, label: {
Image(systemName: "trash")
.padding(5)
.foregroundColor(Color.red)
.background(Color.white)
})
}
}
Approach 3: Find index from the array by object
struct SelectedMedia: Identifiable {
var id = UUID()
var asset: PHAsset
var image: UIImage
}
ForEach(self.selectedMedia, id:\.id) { object in // <-- Here
ZStack {
Image(uiImage: object.image) // <-- Here
.resizable()
.scaledToFit()
.frame(width: UIScreen.main.bounds.width * 0.5)
Button(action: {
if let index = self.selectedMedia.firstIndex(where: {$0.id == object.id}) { // <-- Here
removeItem(at: index) // <-- Here
}
}, label: {
Image(systemName: "trash")
.padding(5)
.foregroundColor(Color.red)
.background(Color.white)
})
}
}