iOS 16.4 SwiftUI:如何让多行TextField始终保持在键盘上方可见?
解决SwiftUI List中多行TextField输入时被键盘遮挡的问题
针对你遇到的List中多行TextField输入内容超过一行后被键盘遮挡的问题,可以通过ScrollViewReader结合焦点跟踪和键盘通知实现自动滚动,确保TextField始终完整显示在键盘上方。
解决方案代码
import SwiftUI struct PlaygroundView: View { let sections = ["Section 1", "Section 2", "Section 3", "Section 4", "Section 5", "Section 6"] @State private var sectionText = Array(repeating: "", count: 6) @FocusState private var focusedIndex: Int? var body: some View { ScrollViewReader { proxy in List { ForEach(sections.indices, id: \.self) { index in Section(header: Text(sections[index])) { TextField("Enter text", text: $sectionText[index], axis: .vertical) .focused($focusedIndex, equals: index) .id("textField-\(index)") .onChange(of: sectionText[index]) { _ in guard focusedIndex == index else { return } withAnimation { proxy.scrollTo("textField-\(index)", anchor: .bottom) } } } } } .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)) { _ in guard let index = focusedIndex else { return } DispatchQueue.main.async { withAnimation { proxy.scrollTo("textField-\(index)", anchor: .bottom) } } } } } }
方案说明
- ScrollViewReader:获取List的滚动控制代理,支持手动定位滚动位置。
- FocusState:跟踪当前正在编辑的TextField索引,确保只对激活的输入框做滚动处理。
- 唯一ID标记:给每个TextField绑定唯一ID,作为滚动定位的目标。
- 文本变化监听:当输入内容变化导致TextField高度增加时,自动滚动到输入框底部,避免新增内容被键盘遮挡。
- 键盘通知监听:在键盘高度发生变化(如切换键盘类型)时,重新调整滚动位置,保持输入框可见。
内容的提问来源于stack exchange,提问作者Victor K
相关产品推荐
相关产品推荐

