SwiftUI 垂直ScrollView内嵌水平ScrollView时TextField唤键盘不上移如何解决
问题背景
垂直ScrollView中嵌套水平ScrollView的场景下,SwiftUI原生的键盘自适应逻辑会失效,ScrollView不会自动上移露出被键盘遮挡的TextField:只有当TextField直接属于外层垂直ScrollView时,系统才会自动滚动外层ScrollView保证输入框可见;嵌套时输入框归属于内层水平ScrollView,系统仅会响应内层滚动,不会触发外层滚动,最终导致输入框被遮挡。
界面正常状态:
键盘唤起后输入框被遮挡的效果:
复现代码
struct ContentView: View { @State var text = "" var body: some View { ScrollView(.vertical, showsIndicators: false) { VStack { ForEach(0..<10) {_ in ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 20) { ForEach(0..<10) {_ in VStack { Rectangle() .fill(Color.red) .frame(width: 500, height: 300) TextField("Test", text: $text) } } } } } } } } }
解决方案
方案一:监听键盘高度手动调整底部内边距(兼容iOS13及以上版本)
通过监听系统键盘弹出/收起的通知,动态给外层ScrollView的内容底部添加和键盘高度一致的内边距,把整个内容区域顶起,保证输入框不会被键盘遮挡,逻辑简单兼容性好。
先添加监听键盘高度的扩展:
import Combine extension View { func getKeyboardHeight() -> AnyPublisher<CGFloat, Never> { let showPublisher = NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification) .map { notification -> CGFloat in let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect ?? .zero return frame.height } let hidePublisher = NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification) .map { _ in CGFloat(0) } return showPublisher.merge(with: hidePublisher) .eraseToAnyPublisher() } }
修改后的业务代码:
struct ContentView: View { @State var text = "" @State private var keyboardHeight: CGFloat = 0 var body: some View { ScrollView(.vertical, showsIndicators: false) { VStack { ForEach(0..<10) {_ in ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 20) { ForEach(0..<10) {_ in VStack { Rectangle() .fill(Color.red) .frame(width: 500, height: 300) TextField("Test", text: $text) } } } } } } .padding(.bottom, keyboardHeight) } .onReceive(getKeyboardHeight()) { height in withAnimation(.easeOut(duration: 0.25)) { keyboardHeight = height } } } }
方案二:ScrollViewReader精准滚动(iOS14及以上版本)
如果需要精准滚动到当前激活的输入框位置,可以配合@FocusState和ScrollViewReader实现,适合多输入框需要精确定位的场景。
struct ContentView: View { @State var text = "" @FocusState private var isInputActive: Bool var body: some View { ScrollViewReader { proxy in ScrollView(.vertical, showsIndicators: false) { VStack { ForEach(0..<10) { index in ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 20) { ForEach(0..<10) {_ in VStack { Rectangle() .fill(Color.red) .frame(width: 500, height: 300) TextField("Test", text: $text) .focused($isInputActive) // 给每个输入框绑定唯一ID .id("input_\(index)") } } } } } } } .onChange(of: isInputActive) { newValue in guard newValue else { return } // 输入框激活时滚动到对应ID的位置 withAnimation(.easeOut(duration: 0.25)) { proxy.scrollTo("input_\(当前激活输入框的对应index)", anchor: .bottom) } } } } }
内容的提问来源于stack exchange,提问作者NilsBerni
相关产品推荐
相关产品推荐

