Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 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 Reply

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())
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...