macOS下SwiftUI TextField获焦取消全选,光标移至文本末尾
macOS下SwiftUI TextField光标定位与TextEditor选中文本问题
一、TextField启动后文本全选,需光标定位到文本末尾
在macOS环境中运行以下SwiftUI TextField代码时,窗口启动后文本会被全选,需求是让光标直接定位在文本末尾(如Testx|)。
struct ContentView: View { @FocusState private var textEditorFocused: Bool @State var textEditor: String = "Testx" var body: some View { VStack { TextField("输入分组名称", text: $textEditor) .focused($textEditorFocused) .font(.system(size: 18, weight: .semibold, design: .default)) .frame(maxWidth: .infinity, alignment: .leading) .textFieldStyle(.plain) .autocorrectionDisabled(true) } .padding() .onAppear { textEditorFocused = true } } }
二、TextEditor替代方案的选中文本问题
尝试用TextEditor替代TextField,但遇到无法选中文本的问题,以下是对应的TextEditor实现代码,寻求解决方法:
struct ContentView: View { @FocusState private var textEditorFocused: Bool @State var textEditorHeight: CGFloat = 20 @State var editMode: Bool = false @State var textEditor: String = "Test is always highlighted" struct ViewHeightKey: PreferenceKey { static var defaultValue: CGFloat { 0 } static func reduce(value: inout Value, nextValue: () -> Value) { value += nextValue() } } var body: some View { // 🟢 这个可以正常选中文本 TextEditor(text: $textEditor) .focused($textEditorFocused) .font(.system(size: 15, weight: .semibold, design: .default)) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .frame(height: max(20, textEditorHeight)) .fixedSize(horizontal: false, vertical: true) .lineSpacing(1) .textFieldStyle(.plain) ZStack(alignment: .leading) { if editMode { // 🔴 这个无法选中文本 TextEditor(text: $textEditor) .focused($textEditorFocused) .font(.system(size: 15, weight: .semibold, design: .default)) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .frame(height: max(20, textEditorHeight)) // 🟡 把20改成80就能选中文本了 .fixedSize(horizontal: false, vertical: true) .lineSpacing(1) .textFieldStyle(.plain) } Text(textEditor) .font(.system(size: 15, weight: .regular, design: .default)) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true) .opacity(editMode ? 0 : 1) .background(Color.white.opacity(0.001)) .onTapGesture { editMode = true textEditorFocused = true } .background(GeometryReader { Color.clear.preference(key: ViewHeightKey.self, value: $0.frame(in: .local).size.height) }) } .onChange(of: editMode) { editMode in if !editMode { textEditorFocused = false } else { textEditorFocused = true } } Button("编辑模式") { editMode.toggle() } } }
内容的提问来源于stack exchange,提问作者swifty-george
相关产品推荐
相关产品推荐

