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
indicesand then get an object from the index.Approach 2: Use
enumerated()it will give you both item object and offset.Approach 3: Find index from the array by object