正如以下人士在答复中所述
Asperi
对于类似的问题
here
,(目前)还不可能使用SwiftUI关闭特定字段的对焦环;然而,
以下解决方法将禁用所有对焦环
NSTextField
应用程序中的实例
:
extension NSTextField {
open override var focusRingType: NSFocusRingType {
get { .none }
set { }
}
}
如果你想在视图中用自己的自定义对焦环替换它
onEditingChanged
参数可以帮助您实现这一点(见下面的示例);然而,不幸的是,在macOS上,当用户键入第一个字母时,而不是当他们第一次点击该字段时(这并不理想),它会被调用。
理论上,你可以使用
onFocusChange
关闭在
focusable
修饰符,但目前似乎没有为这些macOS文本字段调用它(截至macOS 10.15.3)。
public struct SearchTextView: View {
@Binding var searchText: String
@State private var hasFocus = false
#if !os(macOS)
private var backgroundColor = Color(UIColor.secondarySystemBackground)
#else
private var backgroundColor = Color(NSColor.controlBackgroundColor)
#endif
public var body: some View {
HStack {
Spacer()
#if !os(macOS)
Image(systemName: "magnifyingglass")
#else
Image("icons.general.magnifyingGlass")
#endif
TextField("Search", text: self.$searchText, onEditingChanged: { currentlyEditing in
self.hasFocus = currentlyEditing // If the editing state has changed to be currently edited, update the view's state
})
.textFieldStyle(PlainTextFieldStyle())
.foregroundColor(.primary)
.padding(8)
Spacer()
}
.foregroundColor(.secondary)
.background(backgroundColor)
.cornerRadius(12)
.border(self.hasFocus ? Color.accentColor : Color.clear, width: self.hasFocus ? 3 : 0)
.padding()
}
public init(searchText: Binding<String>) {
self._searchText = searchText
}
}