我有以下简化代码:
import SwiftUI
struct ContentView: View {
@FocusState private var isFocused: Bool
@State private var text: String = ""
@State private var items: [String] = ["Item1", "Item2"]
var body: some View {
VStack {
List {
ForEach(items, id: \.self) {
Text($0)
}
TextField("Add item", text: $text)
.focused($isFocused)
.onSubmit {
items.append(text)
text = ""
isFocused = true
}
}
.listStyle(PlainListStyle())
}
}
}
#Preview {
ContentView()
}
我遇到的问题是按下提交时键盘会轻微弹跳。我希望键盘保持活动状态。
VStack {
List {
ForEach(items, id: \.self) { item in
Text(item)
}
HStack { // Use an HStack to contain the TextField
TextField("Add item", text: $text)
.focused($isFocused)
.keyboardType(.default)
Button(action: { // Use a Button for submission
if !text.isEmpty {
items.append(text)
text = ""
// Keep focus on the TextField
DispatchQueue.main.async {
isFocused = true
}
}
}) {
Image(systemName: "plus.circle.fill") // Or any other suitable icon/text
}
.disabled(text.isEmpty) // Disable button when text is empty
}
}
.listStyle(.plain)
}
.onAppear {
DispatchQueue.main.async {
isFocused = true
}
}
您可以使用添加按钮在列表中添加项目 您看到的“弹跳”键盘可能是由于在您追加新项目后列表会自行重绘。随着列表更新,焦点会短暂移动,导致键盘暂时消失并重新出现。