过滤列表项后,ListView中的SwiftUI TextField变为空白 [英] SwiftUI TextField inside ListView goes blank after filtering list items
问题描述
我正在使用一个iOS应用程序,该应用程序显示可以编辑的项目列表.为此,我对每个项目使用 List
和 TextField
.
I'm working on an iOS app that displays a list of items that can be edited. For this, I'm using List
and TextField
for each of these items.
我的应用程序有一些按钮,允许用户筛选此列表中当前显示的信息.我遇到了一个问题,该问题导致 TextField
值在过滤后变为空白,而且我一生无法弄清自己在做什么错.
My application has some buttons that allow the user to filter the information that's currently displayed in this List. I've bumped into an issue that causes the TextField
values to go blank after being filtered, and I can't for the life of me figure out what I'm doing wrong.
这是一个非常基本的复制品:
Here's a very basic reproduction:
import SwiftUI
let allItems = ["1. Foo", "1. Bar", "1. Baz", "2. Goo", "2. Gar", "2. Gaz"]
struct ContentView: View {
@State private var items = [String]()
@State private var filterPrefix = "1"
var body: some View {
NavigationView {
List {
ForEach(items, id: \.self) { item in
RowView(item: item)
}
}
.navigationBarItems(trailing: Button("Toggle") {
self.filterPrefix = (self.filterPrefix == "1" ? "2" : "1")
self.items = allItems.filter { $0.starts(with: self.filterPrefix) }
})
.navigationBarTitle("Items", displayMode: .inline)
}
.onAppear {
self.items = allItems.filter { $0.starts(with: self.filterPrefix) }
}
}
}
struct RowView: View {
var item: String
@State private var inputText = ""
var body: some View {
VStack {
TextField("", text: $inputText)
}
.onAppear {
print("Item: \(self.item)") // This prints the item successfully
self.inputText = self.item
}
}
}
几次点击 Toggle
后, TextField
最终以空白结尾.但是, onAppear
中的代码仍然可以很好地打印文本值.
Upon hitting Toggle
a couple of times, the TextField
eventually ends up empty. However, the code in onAppear
still prints the text value fine.
这是一个gif:
我做错什么了吗?我是否应该仅在单击时抛出 TextField
?(似乎不是一个好主意,但我不知道为什么它不起作用)
Am I doing something wrong? Should I throw in the TextField
only upon clicking? (seems like not a great idea, but I'm at a loss for why this isn't working)
我正在Xcode 11.2 beta 2(11B44)上运行,但是在11.1以及iOS 13.1和13.2上都发生了相同的问题
I'm running on Xcode 11.2 beta 2 (11B44) but the same problem occurs on 11.1 and both iOS 13.1 and 13.2
为了进一步复杂化,我更改了行以包含文本和文本字段:
To further complicate things, I changed the row to include both text and textfield:
HStack {
Text(item)
TextField("", text: $inputText)
}
现在,除非它是列表中的最后一项,否则 TextField
值不会空白.对我来说开始像臭虫了
And now the TextField
value doesn't go blank unless it's the last item in the list. Starting to smell like a bug to me
推荐答案
此问题已在最新的Xcode beta(11.4)中修复
This issue is now fixed in the latest Xcode beta (11.4)
这篇关于过滤列表项后,ListView中的SwiftUI TextField变为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!