How can I get an effect similar to what you see in the images, like it does on xcode.
Also consider the possibility of light and dark themes.
import SwiftUI
struct FindNavigatorSearchBar: View {
@ObservedObject
var state: WorkspaceDocument.SearchState
let title: String
@Binding
var text: String
@FocusState
private var focusState: Bool
var body: some View {
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(Color(nsColor: .secondaryLabelColor))
textField
if !text.isEmpty { clearButton }
}
.padding(.horizontal, 5)
.padding(.vertical, 3)
.background(focusState ? .quaternary : .tertiary)
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.gray, lineWidth: 0.5).cornerRadius(8))
.cornerRadius(8)
}
private var textField: some View {
TextField(title, text: $text)
.focused($focusState)
.disableAutocorrection(true)
.textFieldStyle(PlainTextFieldStyle())
}
private var clearButton: some View {
Button {
self.text = ""
state.search("")
} label: {
Image(systemName: "xmark.circle.fill")
}
.foregroundColor(.secondary)
.buttonStyle(PlainButtonStyle())
}
}
struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
HStack {
FindNavigatorSearchBar(
state: .init(WorkspaceDocument.init()),
title: "placeholder",
text: .constant("value")
)
}
.padding()
}
}
CodePudding user response:
It is possible to use background with focused dependent state, like
.background(RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 0.5).cornerRadius(4)
.background(focused ? .black : .clear) // << here !!
.clipShape(RoundedRectangle(cornerRadius: 4))
)
Complete test module is here