You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)
                    }
                }
            }
        }
    }
}

方案说明

  1. ScrollViewReader:获取List的滚动控制代理,支持手动定位滚动位置。
  2. FocusState:跟踪当前正在编辑的TextField索引,确保只对激活的输入框做滚动处理。
  3. 唯一ID标记:给每个TextField绑定唯一ID,作为滚动定位的目标。
  4. 文本变化监听:当输入内容变化导致TextField高度增加时,自动滚动到输入框底部,避免新增内容被键盘遮挡。
  5. 键盘通知监听:在键盘高度发生变化(如切换键盘类型)时,重新调整滚动位置,保持输入框可见。

内容的提问来源于stack exchange,提问作者Victor K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:05:17