MacOs SwiftUI textfield 焦点效果颜色变化

MacOs SwiftUI textfield focus effect color change

如何获得与您在图像中看到的效果类似的效果,就像在 xcode 上一样。

还要考虑浅色和深色主题的可能性。


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()
    }
}

可以使用具有聚焦依赖状态的背景,例如

.background(RoundedRectangle(cornerRadius: 4)
        .stroke(Color.gray, lineWidth: 0.5).cornerRadius(4)
        .background(focused ? .black : .clear)        // << here !!
        .clipShape(RoundedRectangle(cornerRadius: 4))
)

完成test module is here