当键盘在视图中时,SwiftUI文本字段填充



我有一个Scrollview,里面只有文本字段。我希望能够点击任何文本字段,并让键盘稍微向上推。

struct DetailView: View {
@EnvironmentObject var vm: ViewModel
var body: some View {
ScrollView {
VStack {
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
Group {
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
TextField("Enter stuff", text: $vm.username)
.padding(.bottom, 20)
}
}
}
}
}

当文本字段中没有填充/样式时,这非常有效。如果我使用带有样式(边框、填充(的自定义文本字段,键盘会悬停在部分文本字段上。这是我的自定义文本字段:

struct NotesField: View {
@Binding var value: String
init(_ value: Binding<String>) {
self._value = value
}
var body: some View {
TextField("Enter stuff", text: $value)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray, lineWidth: 1)
)
}
}

众所周知,ios14会自动为您处理此问题,所以我想要一个解决方案,当键盘打开或不打开时,我不必使用视图修饰符来监听。

如果您使用带有滚动视图的iOS 14+,或者可以选择使用滚动视图。

https://developer.apple.com/documentation/swiftui/scrollviewproxyhttps://developer.apple.com/documentation/swiftui/scrollviewreader

以下内容可能有助于

ScrollViewReader { (proxy: ScrollViewProxy) in
ScrollView {
view1().frame(height: 200)
view2().frame(height: 200)
view3() <-----this has textfields 
.onTapGesture {
proxy.scrollTo(1, anchor: .center)
}
.id(1)
view4() <-----this has text editor
.onTapGesture {
proxy.scrollTo(2, anchor: .center)
}
.id(2)
view5().frame(height: 200)
view6().frame(height: 200)
submtButton().frame(height: 200)
}
}

上面的重要部分是

anyView().onTapGesture {
proxy.scrollTo(_ID, anchor: .center)
}.id(_ID)

希望这能帮助到某人:(

相关内容

  • 没有找到相关文章

最新更新