Issue #636
Normally we can just wrap NSTextField
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
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))