问题描述
我在 SwiftUI 2.0 和 iOS14 中遇到了非常奇怪的行为.
I am experiencing very odd behavior in SwiftUI 2.0 and iOS14.
当键盘出现在屏幕上时,自动调用其他标签视图的 OnAppear 方法.
When the keyboard appears on the screen, the OnAppear method of other tab's view called automatically.
但是,这在 Xcode 11.7 中运行良好
However, this works fine Xcode 11.7
这是实际问题.
这是产生上述错误的代码.
Here is the code which produces the above error.
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 的一个错误,但不确定.任何帮助将不胜感激.
This seems to be a bug of SwiftUI 2.0 but not sure.Any help will be appreciated.
谢谢
推荐答案
我自己也有同样的问题,我认为这是一个错误或类似的问题,但是我想出了一个解决方案,也许是一种解决方法,直到 Apple 修复它.
Having the same issue myself, I think this is a bug or something like that, however I came up with a solution maybe a workaround until apple will fix it.
我所做的事情基本上是我使用了一个 LazyVStack
,这似乎工作得很好.
The thing that I did is basically I used a LazyVStack
, and this seems to be working perfectly.
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
方法不会在键盘出现时自动调用.
Now the OnAppear
method of other tab's view it is not called automatically when the keyboard appear.
这篇关于当键盘出现在 SwiftUI 中时 OnAppear 意外调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!