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

如何阻止SwiftUI TextField执行「智能编辑」功能?

关闭SwiftUI TextField的「智能编辑」功能

要关闭SwiftUI TextField中那些默认的智能编辑行为(比如双空格转句号、三点转省略号、直引号转弯引号),可根据iOS版本选择对应实现方式:

iOS 15+(推荐)

苹果在iOS 15为SwiftUI TextField新增了三个专门修饰符,可直接关闭对应智能编辑功能:

  • 关闭双空格自动转句号:.smartPeriodsDisabled(true)
  • 关闭直引号自动转弯引号:.smartQuotesDisabled(true)
  • 关闭自动转换破折号(如--转—):.smartDashesDisabled(true)

结合关闭自动纠正与自动大写的设置,完整示例代码如下:

TextField("输入内容", text: $inputText)
    .disableAutocorrection(true)
    .textInputAutocapitalization(.none)
    .smartPeriodsDisabled(true)
    .smartQuotesDisabled(true)
    .smartDashesDisabled(true)

iOS 14及以下

若需兼容更低版本,需通过UIViewRepresentable封装原生UITextField,手动关闭相关属性:

struct PlainTextField: UIViewRepresentable {
    @Binding var text: String
    var placeholder: String
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.placeholder = placeholder
        // 关闭自动纠正
        textField.autocorrectionType = .no
        // 关闭自动大写
        textField.autocapitalizationType = .none
        // 关闭智能引号、破折号、句号转换
        textField.smartQuotesType = .no
        textField.smartDashesType = .no
        textField.smartInsertDeleteType = .no
        textField.delegate = context.coordinator
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: PlainTextField
        
        init(_ parent: PlainTextField) {
            self.parent = parent
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
    }
}

// 使用方式
PlainTextField(text: $inputText, placeholder: "输入内容")

以上配置可完全关闭所有不需要的智能编辑行为,让TextField保留输入的原始内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:46:00