fix(process): 恢复系统原生搜索框样式
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// System search-field appearance, editing and cancel button without custom chrome.
|
||||
struct NativeSearchField: NSViewRepresentable {
|
||||
@Binding var text: String
|
||||
@Binding var isFocused: Bool
|
||||
var placeholder: String
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSSearchField {
|
||||
let field = NSSearchField()
|
||||
field.delegate = context.coordinator
|
||||
field.target = context.coordinator
|
||||
field.action = #selector(Coordinator.searchChanged(_:))
|
||||
field.sendsSearchStringImmediately = true
|
||||
field.sendsWholeSearchString = false
|
||||
field.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||
return field
|
||||
}
|
||||
|
||||
func updateNSView(_ field: NSSearchField, context: Context) {
|
||||
context.coordinator.parent = self
|
||||
field.placeholderString = placeholder
|
||||
field.setAccessibilityLabel(placeholder)
|
||||
if field.stringValue != text { field.stringValue = text }
|
||||
if !isFocused, field.currentEditor() != nil { field.window?.makeFirstResponder(nil) }
|
||||
}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSSearchField, context: Context) -> CGSize? {
|
||||
CGSize(width: proposal.width ?? 220, height: nsView.intrinsicContentSize.height)
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, NSSearchFieldDelegate {
|
||||
var parent: NativeSearchField
|
||||
init(_ parent: NativeSearchField) { self.parent = parent }
|
||||
@objc func searchChanged(_ field: NSSearchField) { parent.text = field.stringValue }
|
||||
func controlTextDidChange(_ notification: Notification) {
|
||||
guard let field = notification.object as? NSSearchField else { return }
|
||||
parent.text = field.stringValue
|
||||
}
|
||||
func controlTextDidBeginEditing(_ notification: Notification) { parent.isFocused = true }
|
||||
func controlTextDidEndEditing(_ notification: Notification) { parent.isFocused = false }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user