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

SwiftUI中TextEditor占位符与光标不同行问题的解决方法

解决SwiftUI TextEditor占位符与光标不同行的问题

问题出在TextEditor默认带有内置内边距,而你叠加在上方的占位符Text没有匹配这个内边距,导致两者位置错开。

直接调整占位符的内边距,让它和TextEditor的默认内边距对齐即可,同时添加点击穿透确保TextEditor能正常获取焦点:

ZStack(alignment: .topLeading) {
    VStack {
        TextEditor(text: $currentText)
            .rchFont(.rchBody, .primaryLighter)
            .frame(maxWidth: .infinity, alignment: .leading)
            .onChange(of: currentText) { value in
                if value.count > 1000 {
                    currentText = oldText
                    return
                }
                oldText = currentText
                currentCharCount = "\(value.count)"
            }
        
        Spacer()
        
        Text("\(currentCharCount)/1000")
            .rchFont(.rchBody, .primaryLighter)
            .frame(maxWidth: .infinity, alignment: .trailing)
        
        RCHButtonPrimary(title: messageButtonTitle) {
            text = currentText
            presentationMode.wrappedValue.dismiss()
        }
    }
    if currentText.isEmpty {
        Text(placeholder)
            .rchFont(.rchBody, .textSupport)
            .padding(.top, 8) // 匹配TextEditor顶部内边距
            .padding(.leading, 4) // 匹配TextEditor左侧内边距
            .frame(maxWidth: .infinity, alignment: .leading)
            .allowsHitTesting(false) // 允许点击穿透到下方的TextEditor
    }
}

补充说明:

  • 不同iOS版本或自定义字体可能会让TextEditor的内边距有细微差异,你可以根据实际预览效果微调padding的数值。
  • allowsHitTesting(false)很关键,它能保证用户点击占位符区域时,焦点会落在TextEditor上而不是被占位符文本拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:57:44