此問題與 iPhone 12 應用程式的 SwiftUI 相關,使用 xcode 13.1。我在每一行中構建了一個帶有 TextField 的串列,但是每次我嘗試編輯內容時,只允許我點擊一次并只輸入一個字符,然后不能再繼續輸入字符,除非我再次點擊然后輸入另一個字符.我是不是寫錯了什么代碼?
class PieChartViewModel: ObservableObject, Identifiable {
@Published var options = ["How are you", "你好", "Let's go to zoo", "OKKKKK", "什麼情況??", "yesssss", "二百五", "明天見"]
}
struct OptionsView: View {
@ObservedObject var viewModel: PieChartViewModel
var body: some View {
NavigationView {
List {
ForEach($viewModel.options, id: \.self) { $option in
TextField(option, text: $option)
}
}
.navigationTitle("Options")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button {
addNewOption()
} label: {
HStack {
Image(systemName: "plus")
Text("Create a new option")
}
}
}
}
}
}
func addNewOption() {
viewModel.options.insert("", at: viewModel.options.count)
}
}
struct OptionsView_Previews: PreviewProvider {
static var previews: some View {
let pieChart = PieChartViewModel()
OptionsView(viewModel: pieChart)
}
}
uj5u.com熱心網友回復:
歡迎使用 StackOverflow!你的問題是,你是直接的更新ObservableObject中TextField。您對模型所做的每一次更改都會導致您的視圖重繪,當然,這會將您的注意力從TextField. 最簡單的答案是Binding在TextField. 這將導致模型更新,而無需不斷重繪您的視圖:
struct OptionsView: View {
// You should be using @StateObject instead of @ObservedObject, but either should work.
@StateObject var model = PieChartViewModel()
@State var newText = ""
var body: some View {
NavigationView {
VStack {
List {
ForEach(model.options, id: \.self) { option in
Text(option)
}
}
List {
//Using Array(zip()) allows you to sort by the element, but use the index.
//This matters if you are rearranging or deleting the elements in a list.
ForEach(Array(zip(model.options, model.options.indices)), id: \.0) { option, index in
// Binding implemented here.
TextField(option, text: Binding<String>(
get: {
model.options[index]
},
set: { newValue in
//You can't update the model here because you will get the same behavior
//that you were getting in the first place.
newText = newValue
}))
.onSubmit {
//The model is updated here.
model.options[index] = newText
newText = ""
}
}
}
.navigationTitle("Options")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button {
addNewOption()
} label: {
HStack {
Image(systemName: "plus")
Text("Create a new option")
}
}
}
}
}
}
}
func addNewOption() {
model.options.insert("", at: model.options.count)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361696.html
