我在 SwiftUI 2.0 和 iOS14 中遇到了非常奇怪的行为。
当键盘出现在屏幕上时,自动调用其他选项卡 View 的 OnAppear 方法。
但是,这很好用 Xcode 11.7
这是行动中的问题。
这是产生上述错误的代码。
struct ContentView: View {
var body: some View {
TabView {
DemoView(screenName: "Home")
.tabItem {
Image.init(systemName: "star.fill")
Text("Home")
}
DemoView(screenName: "Result")
.tabItem {
Image.init(systemName: "star.fill")
Text("Result")
}
DemoView(screenName: "More")
.tabItem {
Image.init(systemName: "star.fill")
Text("More")
}
}
}
}
struct DemoView:View {
@State var text:String = ""
var screenName:String
var body: some View {
VStack{
Text(screenName)
.font(.title)
TextField("Buggy Keyboard Issue", text: $text)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("Issue : When keyboard appears, onAppear of other 2 tabs call automatically.")
.font(.footnote)
}
.padding()
.onAppear(perform: {
debugPrint("OnAppear of : \(screenName)")
})
}
}
这似乎是 SwiftUI 2.0 的一个错误,但不确定。任何帮助将不胜感激。
谢谢
最佳答案
我自己也有同样的问题,我认为这是一个错误或类似的问题,但是我想出了一个解决方案,也许是一种解决方法,直到苹果修复它。
我所做的事情基本上是我使用了 LazyVStack
,这似乎工作得很好。
LazyVStack {
VStack{
Text(screenName)
.font(.title)
TextField("Buggy Keyboard Issue", text: $text)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("Issue : When keyboard appears, onAppear of other 2 tabs call automatically.")
.font(.footnote)
}
.padding()
.onAppear(perform: {
debugPrint("OnAppear of : \(screenName)")
})
}
现在OnAppear
其他选项卡 View 的方法不会在键盘出现时自动调用。关于keyboard - 当键盘出现在 SwiftUI 中时 OnAppear 意外调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64027482/