我有一个文本视图列表,我想在按下一个键后切换焦点.我有一个 struct 体,它代表我的文本字段数据:
struct WordEntry : BaseIndexStruct, Identifiable, Equatable, Hashable{
let id = UUID()
var word : String = ""
var index : Int
init(index: Int) {
self.index = index
}
}
然后我有了一个控制焦点的文本字段的视图,我在这里添加了一条print语句来查看word.index==Focus!实际上从来都是真的.它确实变成了真的,但是设置isFocused没有影响,在打印期间它仍然是假的.
struct SolvedField: View {
@State var word: WordEntry
@FocusState var isFocused: Bool
@Binding var focus: Int?
var nextFocus: (Int) -> Void
var body: some View {
TextField("", text: $word.word)
.onChange(of: focus, perform: { newValue in
if(focus != nil){
self.isFocused = word.index == focus!
print("index \(word.index), focus \(focus!), isfocused: \(self.isFocused) should be focused \(word.index == focus!)")
}
})
.focused(self.$isFocused)
.submitLabel(.next)
.onSubmit {
isFocused = false
self.nextFocus(word.index)
}
}
}
然后是包含单词条目列表的视图,这些单词条目随后被显示为文本字段控件.
struct SolvedLettersLine: View {
@State var words = [WordEntry(index: 0), WordEntry(index: 1), WordEntry(index: 2), WordEntry(index: 3)]
@State var focus : Int?
var body: some View {
VStack(spacing:10){
Group{
ForEach(words) { word in
SolvedField(word: word, focus: $focus, nextFocus:{
focus = $0 + 1
})
}
}
}
}
不幸的是,我完全被困在如何让iOS将Textfield焦点切换到工作上,有人知道吗?