我在我的视图中使用 TextField,当它成为第一响应者时,它会离开视图,如下面的 GIF 所示。
有什么办法可以摆脱这种行为吗?
这是我的代码
NavigationView(content: {
ZStack{
MyTabView(selectedIndex: self.$index)
.view(item: self.item1) {
NewView(title: "Hello1").navigationBarTitle("")
.navigationBarHidden(true)
}
.view(item: self.item2) {
NewView(title: "Hello2").navigationBarTitle("")
.navigationBarHidden(true)
}
.view(item: self.item3) {
NewView(title: "Hello3").navigationBarTitle("")
.navigationBarHidden(true)
}
}.navigationBarHidden(true)
.navigationBarTitle("")
}).ignoresSafeArea(.keyboard, edges: .bottom)
Run Code Online (Sandbox Code Playgroud)
// 新视图
struct NewView:View {
@State var text:String = ""
var title:String
var body: some View {
VStack {
Spacer()
Text("Hello")
TextField(title, text: self.$text)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.padding()
.onAppear {
debugPrint("OnApper \(self.title)")
}
}
}
Run Code Online (Sandbox Code Playgroud) 尽管使用了修饰符,我的 SwiftUI 视图仍被键盘上推.ignoresSafeArea(.keyboard):
import SwiftUI
struct PushUpView: View {
@State var random = ""
var body: some View {
ZStack(alignment: .top) {
Color.clear
VStack {
ForEach(0..<25) { id in
Text("Text: \(id)")
}
TextField("Hello, World!", text: $random)
Spacer()
}
}
.ignoresSafeArea(.keyboard)
}
}
Run Code Online (Sandbox Code Playgroud)
根据以下主题:
我认为通过使用Spacer(),并将键盘避免器放在ZStack背景Color.clear占据所有可用空间的背景上,我会很安全。
唉,问题仍然存在。我究竟做错了什么?
我是 SwiftUI 编程新手,我已经创建了一个视图,但是一旦用户点击文本字段,键盘就会出现,整个视图就会向上推,我该如何解决这个问题?