You need to enable JavaScript to run this app. iOS 14下SwiftUI中Form内TextEditor自动键盘规避功能失效问题问询
优惠活动
大模型
产品
解决方案
定价
更多

iOS 14下SwiftUI中Form内TextEditor自动键盘规避功能失效问题问询

Form 键盘规避失效问题解决方案

根因

iOS 端 SwiftUI 的 Form 底层是封装 UITableView 实现的,它自带的滚动逻辑会和系统默认的全局键盘规避逻辑冲突,所以默认不会自动上推被键盘遮挡的输入区域。

修复方案

1. iOS 16 及以上版本

直接添加 scrollDismissesKeyboard 修饰符即可触发自动滚动避让,代码修改如下:

import SwiftUI
struct ContentView: View {
    @State private var stopLocation: String = ""
    var body: some View {
        Form {
            let desc = "\n\n\n\n\n\n\n\n\n\n\n\nEnter Location"
            Text(desc)
            VStack {
                TextEditor(text: $stopLocation)
            }
        }
        // 可按需选择模式:.interactively 滚动时隐藏键盘 / .automatic 系统自动判断
        .scrollDismissesKeyboard(.automatic)
    }
}

2. 全 iOS 版本兼容

如果需要兼容 iOS 15 及更早版本,可以手动监听键盘高度变化,动态调整 Form 的底部内边距实现避让:

import SwiftUI
import Combine

struct ContentView: View {
    @State private var stopLocation: String = ""
    @State private var keyboardHeight: CGFloat = 0
    
    private let keyboardPublisher = Publishers.Merge(
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
            .map { notification in
                (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0
            },
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
            .map { _ in CGFloat(0) }
    )
    .eraseToAnyPublisher()
    
    var body: some View {
        Form {
            let desc = "\n\n\n\n\n\n\n\n\n\n\n\nEnter Location"
            Text(desc)
            VStack {
                TextEditor(text: $stopLocation)
            }
        }
        .padding(.bottom, keyboardHeight)
        .animation(.easeOut(duration: 0.25), value: keyboardHeight)
        .onReceive(keyboardPublisher) { keyboardHeight = $0 }
    }
}

注意:如果项目已经全局配置了底部安全区忽略,需要在计算内边距时减去底部安全区高度,避免底部留白过大。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 07:21:00