I used the below code to create a custom search bar in SwiftUI. It works great on iOS / Catalyst:
...but when running natively on macOS, the 'focus ring' highlighted border styling (when the user selects the text field) rather ruins the effect:
Using .textFieldStyle(PlainTextFieldStyle())
has removed most of the default styling from the underlying field (which I believe is an NSTextField
), but not the focus ring.
Is there a way to remove this too? I tried creating a custom TextFieldStyle
and applying that, but couldn't find any modifier to style that border.
public struct SearchTextView: View {
@Binding var searchText: String
#if !os(macOS)
private let backgroundColor = Color(UIColor.secondarySystemBackground)
#else
private let 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)
.textFieldStyle(PlainTextFieldStyle())
.foregroundColor(.primary)
.padding(8)
Spacer()
}
.foregroundColor(.secondary)
.background(backgroundColor)
.cornerRadius(12)
.padding()
}
public init(searchText: Binding<String>) {
self._searchText = searchText
}
}
As of iOS 17 / macOS 14, you can use .focusEffectDisabled
.
You can also apply it to buttons or the entire view.
TextField("Search", text: self.$searchText)
.focusEffectDisabled()