简体   繁体   中英

MacOs SwiftUI textfield focus effect color change

在此处输入图像描述

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM