Issue #620
For NSWindow
having level
other than .normal
, need to override key and main property to allow TextField to be focusable
class FocusWindow: NSWindow {
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { true }
}
Furthermore to customize TextField, consider using custom
import SwiftUI
import AppKit
struct MyTextField: NSViewRepresentable {
@Binding var text: String
func makeNSView(context: NSViewRepresentableContext<MyTextField>) -> NSTextField {
let tf = NSTextField()
tf.focusRingType = .none
tf.isBordered = false
tf.drawsBackground = false
tf.delegate = context.coordinator
return tf
}
func updateNSView(_ nsView: NSTextField, context: NSViewRepresentableContext<MyTextField>) {
nsView.stringValue = text
}
func makeCoordinator() -> MyTextField.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, NSTextFieldDelegate {
let parent: MyTextField
init(parent: MyTextField) {
self.parent = parent
}
func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as! NSTextField
parent.text = textField.stringValue
}
}
}