Issue #636
Normally we can just wrap NSTextField
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| struct SearchTextField: NSViewRepresentable { @Binding var text: String var hint: String var onCommit: (String) -> Void
func makeNSView(context: NSViewRepresentableContext<SearchTextField>) -> NSTextField { let tf = NSTextField() tf.focusRingType = .none tf.isBordered = false tf.isEditable = true tf.isSelectable = true tf.drawsBackground = false tf.delegate = context.coordinator tf.font = NSFont(name: OpenSans.bold.rawValue, size: 14) tf.placeholderString = hint return tf }
func updateNSView( _ nsView: NSTextField, context: NSViewRepresentableContext<SearchTextField> ) { nsView.font = NSFont(name: OpenSans.bold.rawValue, size: 14) nsView.stringValue = text }
func makeCoordinator() -> SearchTextField.Coordinator { Coordinator(parent: self) }
class Coordinator: NSObject, NSTextFieldDelegate { let parent: SearchTextField init(parent: SearchTextField) { self.parent = parent }
func controlTextDidChange(_ obj: Notification) { let textField = obj.object as! NSTextField parent.text = textField.stringValue }
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if (commandSelector == #selector(NSResponder.insertNewline(_:))) { self.parent.onCommit(textView.string) return true } else { return false } } } }
|
But there is a weird Appstore rejection where the textfield is not focusable. The workaround is to use TextField
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| extension NSTextField { open override var focusRingType: NSFocusRingType { get { .none } set { } } }
TextField( "What's next?", text: $text, onCommit: { self.onAdd(self.text) } ) .font(.system(size: 14, weight: .semibold, design: .rounded)) .textFieldStyle(PlainTextFieldStyle()) .padding(1) .background(RoundedRectangle(cornerRadius: 2).stroke(Color.white))
|