Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

ios - SwiftUI: Deleting last row in ForEach

I am trying to remove rows inside a ForEach. Removing the last row always throws an index out of range exception. Removing any other row does not.

ForEach(Array(player.scores.enumerated()), id: .element) { index, score in
    HStack {
        if self.isEditSelected {
            Button(action: {
                self.player.scores.remove(at: index)
            }, label: {
                Image("delete")
            })
        }        
        TextField("(score)", value: self.$player.scores[index], formatter: NumberFormatter())
    }
}

I have tried using ForEach(player.indices...) & ForEach(player.scores...), but see the same problem.

Looks to me like the crash happens here self.$player.scores[index], as hardcoding the index to any value other that the last row is working.

Does anyone know how to fix this? Or if there is a better approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is fix

ForEach(Array(player.scores.enumerated()), id: .element) { index, score in
    HStack {
        if self.isEditSelected {
            Button(action: {
                self.player.scores.remove(at: index)
            }, label: {
                Image("delete")
            })
        }        
        TextField("(score)", value: Binding(   // << use proxy binding !!
            get: { self.player.scores[index] },
            set: { self.player.scores[index] = $0 }), 
            formatter: NumberFormatter())
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...