macos - 在 SwiftUI 中禁用 macOS 对焦环

标签 macos cocoa swiftui

是否可以在 swiftUI for Mac 中禁用 TextField 周围的焦点环?

最佳答案

我也有这个问题,经过几个小时的摆弄,答案似乎是否定的。但是,可以包装 NSTextField 并去掉焦点环。

以下代码已在最新版本中经过测试。

struct CustomTextField: NSViewRepresentable {
    @Binding var text: String

    init(text: Binding<String>) {
        _text = text
    }

    func makeNSView(context: Context) -> NSTextField {
        let textField = NSTextField(string: text)
        textField.delegate = context.coordinator
        textField.isBordered = false
        textField.backgroundColor = nil
        textField.focusRingType = .none
        return textField
    }

    func updateNSView(_ nsView: NSTextField, context: Context) {
        nsView.stringValue = text
    }

    func makeCoordinator() -> Coordinator {
        Coordinator { self.text = $0 }
    }

    final class Coordinator: NSObject, NSTextFieldDelegate {
        var setter: (String) -> Void

        init(_ setter: @escaping (String) -> Void) {
            self.setter = setter
        }

        func controlTextDidChange(_ obj: Notification) {
            if let textField = obj.object as? NSTextField {
                setter(textField.stringValue)
            }
        }

    }

}

关于macos - 在 SwiftUI 中禁用 macOS 对焦环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57448578/

相关文章:

swift - Firebase Analytics - 记录 screen_view 在 SwiftUI 中不起作用

macos - 禁用 NSTask 截图声音

ios - SwiftUI - 检查图像是否存在

xcode - undefined symbol ___llvm_profile_runtime

iphone - AVAudioPlayer iPhone 问题

cocoa - 出现双状态项目图标

iphone - 在 Objective-C 中动态加载类?

html - 从 html 中提取表格到命令行中的 excel

macos - 上传表单在 Mac OS X 的 Firefox 3 中不起作用?

objective-c - 同时以编程方式缩小 NSWindows 数组的规模?