请帮助我,如果数组中没有元素,我无法禁用该按钮。我希望按钮在没有元素的情况下不会出现。我知道需要应用什么。禁用但我还无法实现它
import SwiftUI
struct TestModel {
var text: String?
var ansver: [String]
var correctAnswer: String?
}
var test: [TestModel] = [
TestModel(text: "one", ansver: ["one", "two", "three", "four"], correctAnswer: "one"),
TestModel(text: "five", ansver: ["five", "six", "seven", "eight"], correctAnswer: "five"),
TestModel(text: "nine", ansver: ["nine", "ten", "twelve"], correctAnswer: "nine") // 3 values
]
如果删除一个值答案:[“九”,“十”,“十二”] /线程1:致命错误:索引超出范围
struct ContentView: View {
@State var i: Int = 0
@State var score = 0
//@State var scoree = Bool()
var body: some View {
VStack {
if(self.i < test.count) {
Text(test[self.i].text!)
Button(action: {
self.buttonAction(n: "")
}, label: {
Text((test[self.i].ansver[0]))
.foregroundColor(.black)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue,lineWidth: 2)
)
})
Button(action: {
self.buttonAction(n: "")
}, label: {
Text((test[self.i].ansver[1]))
.foregroundColor(.black)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue,lineWidth: 2)
)
})
Button(action: {
self.buttonAction(n: "")
}, label: {
Text((test[self.i].ansver[2]))
.foregroundColor(.black)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue,lineWidth: 2)
)
})
Button(action: {
self.buttonAction(n: "")
}, label: {
Text((test[self.i].ansver[3])) // Thread 1: Fatal error: Index out of range
.foregroundColor(.black)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue,lineWidth: 2)
)
})
}
}
.padding()
}
func buttonAction( n: String){
if(test[self.i].correctAnswer == n) {
self.score = self.score + 1
}
self.i = self.i + 1
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我试图做到这一点,但什么也没发生。大家好。