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

SwiftUI:List内容在键盘弹出/隐藏时跳动问题的解决求助

解决List在键盘弹出/隐藏时的内容跳动问题

核心方案

通过safeAreaInset嵌入输入框,配合背景填充与安全区域忽略设置,同时解决键盘弹出时的内容跳动和键盘隐藏时的过度下移问题。

完整代码

import SwiftUI

struct ContentView: View {
    @State var input: String = ""
    @State private var keyboardIsVisible = false
    
    var body: some View {
        List((1...40), id: \.self) { index in
            row(forIndex: index)
                .padding(.bottom)
                .listRowSeparator(.hidden)
                .listRowInsets(.init())
        }
        .listStyle(.plain)
        .safeAreaInset(edge: .bottom, spacing: 0) {
            TextField("Input", text: $input)
                .padding(.horizontal, 15)
                .foregroundColor(.blue)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding(.vertical, 8)
                .background(Color(UIColor.systemBackground))
                .ignoresSafeArea(.keyboard, edges: .bottom)
        }
        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
            keyboardIsVisible = true
        }
        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
            keyboardIsVisible = false
        }
    }

    func row(forIndex index: Int) -> some View {
        Text("# \(index)")
            .frame(maxWidth: .infinity)
            .background(index % 2 == 0 ? .yellow : .green)
    }
}

关键调整说明

  • safeAreaInset设置spacing: 0:消除输入框与List之间的默认间隙,避免不必要的布局偏移。
  • 输入框添加背景色:防止List内容透过输入框区域显示,保证视觉层级清晰。
  • .ignoresSafeArea(.keyboard, edges: .bottom):键盘隐藏时,输入框自动贴合底部安全区域,不会额外占用空间导致List下移;键盘弹出时,输入框跟随键盘上移,避免List内容跳动。
  • 键盘状态监听:可根据键盘显示状态做更精细的布局调整,代码中已包含基础监听逻辑,可按需扩展。

问题根源解析

  • 最初的VStack布局中,TextField随键盘上移时,List会重新计算布局并占用TextField原本的空间,导致内容瞬间被推到底部。
  • 直接使用safeAreaInset时,输入框默认会占据底部安全区域空间,键盘隐藏时List被向下推送,出现过度下移故障;添加背景色和安全区域忽略设置后,输入框自动适配安全区域,解决了该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:05:20