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

SwiftUI TextField点击文本外时selectedTextRange不生效问题求助

问题:数字类型TextField点击空白区域时光标无法定位到文本末尾
  • 需求:数字类型的TextField,点击时光标自动定位到文本末尾
  • 问题:点击TextField已有文本区域时功能正常,但点击文本以外的空白区域时,光标位置不会改变

相关代码:

struct ContentView: View {
    @State var sourceVal: Double = 100.0
    @FocusState var focusedField: String?

    var body: some View {
        VStack {
            HStack {
                Text("hide keyboard")
                    .onTapGesture {
                        print("sai hide keyboard")
                        self.focusedField = nil
                    }
            }
            HStack {
                Text("Enter Value: ")
                    .font(.title3.bold())
                TextField(String(sourceVal), value: $sourceVal, format: .number)
                    .textFieldStyle(.roundedBorder)
                    .multilineTextAlignment(.trailing)
                    .minimumScaleFactor(0.7)
                    .keyboardType(.decimalPad)
                    .focused($focusedField, equals: "Source")
                    .onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
                        print("yes tapped on me")
                        if let textField = obj.object as? UITextField {
                            print("trying to set it")
                            textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
                        }
                    }
            }
        }
        .padding()
    }
}

演示动图:
演示动图


修复方案

问题根源:点击空白区域时,系统会在textDidBeginEditingNotification触发后,自动将光标调整到点击的空白位置,覆盖了我们设置的光标位置。

只需修改onReceive中的代码,添加短暂延迟后再设置光标位置,确保操作在系统默认调整之后执行:

修改后的完整代码:

struct ContentView: View {
    @State var sourceVal: Double = 100.0
    @FocusState var focusedField: String?

    var body: some View {
        VStack {
            HStack {
                Text("hide keyboard")
                    .onTapGesture {
                        print("sai hide keyboard")
                        self.focusedField = nil
                    }
            }
            HStack {
                Text("Enter Value: ")
                    .font(.title3.bold())
                TextField(String(sourceVal), value: $sourceVal, format: .number)
                    .textFieldStyle(.roundedBorder)
                    .multilineTextAlignment(.trailing)
                    .minimumScaleFactor(0.7)
                    .keyboardType(.decimalPad)
                    .focused($focusedField, equals: "Source")
                    .onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
                        guard let textField = obj.object as? UITextField else { return }
                        // 延迟执行,覆盖系统默认的光标位置
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
                            textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument)
                        }
                    }
            }
        }
        .padding()
    }
}

修改后,无论点击TextField的文本区域还是空白区域,光标都会自动定位到文本末尾。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:24:18