Home > Enterprise >  how can i remove any image from an array by clicking ? i try it with .remove (at:0) but it didn'
how can i remove any image from an array by clicking ? i try it with .remove (at:0) but it didn'

Time:08-10

enter image description here

How can i remove any image from an array by clicking? I try it with .remove (at:0) but it didn't work. It removes only in order and my goal is to remove any of them.

ForEach(mediaItems.items,id: \.id) {    item in
    ZStack{
        HStack {
            if item.mediaType == .photo {
                Image(uiImage:item.photo ?? UIImage())
                    .resizable()
                    .frame(width: 112, height: 90)
                    .cornerRadius(13)
            } else if item.mediaType == .video {
                if let url = item.url {
                    VideoPlayer(player: AVPlayer(url: url))
                        .frame(minHeight: 200)
                } else { EmptyView() }
            }
            
        }
        
        
        
        Image("Tracé 2424")
            .offset(x: 40, y: -30)
            .onTapGesture{
                //        mediaItems.items.remove(at:0)
            }
        
        
    }
} //foreach

CodePudding user response:

Use .enumerated() to get an index for each item. You'll need to change:

ForEach(mediaItems.items, id: \.id) { item in

to:

ForEach(Array(mediaItems.items.enumerated()), id: \.1.id) { index, item in

and then use index in mediaItems.items.remove(at: index):

ForEach(Array(mediaItems.items.enumerated()), id: \.1.id) { index, item in
    ZStack {
        HStack {
            if item.mediaType == .photo {
                Image(uiImage:item.photo ?? UIImage())
                    .resizable()
                    .frame(width: 112, height: 90)
                    .cornerRadius(13)
            } else if item.mediaType == .video {
                if let url = item.url {
                    VideoPlayer(player: AVPlayer(url: url))
                        .frame(minHeight: 200)
                } else { EmptyView() }
            }
                                
        }
                                                                   
        Image("Tracé 2424")
            .offset(x: 40, y: -30)
            .onTapGesture {
                mediaItems.items.remove(at: index)
        }
                                    
    }
} //foreach

Alternate method: Filter array based on id

Since each item has a unique id, you can filter your array and keep items that don't have the same id as the current item:

Replace:

mediaItems.items.remove(at:0)

with:

mediaItems.items = mediaItems.items.filter { $0.id != item.id }

CodePudding user response:

can u try it

mediaItems.item =  mediaItems.item.map { $0.id != item.id }
  • Related