I'm developing a macOS application and facing an issue with NSTextField delegates after refactoring my code. Here's the situation:
I have an NSWindowController.
Inside the NSWindowController, there's a container NSView named containerView.
On top of containerView, I added a custom NSView subclass named MyDetailsView.
MyDetailsView has two NSTextField instances, and their delegates are properly set. The delegate methods like controlTextDidChange(_:) were getting called as expected.
Due to some additional requirements, I refactored MyDetailsView into MyDetailsViewController, a subclass of NSViewController.
I created a corresponding .xib file for MyDetailsViewController.
Updated the code to load and add MyDetailsViewController's view (view property) to containerView.
Verified that the NSTextField delegates are still being set, and the fields are displayed correctly in the UI.
However, after this refactor, the NSTextField delegate methods (e.g., controlTextDidChange(_:)) are no longer being triggered.
**What I've Tried: ** Verified that the delegates for the NSTextField instances are correctly set after the refactor. Ensured that the MyDetailsViewController's view is added to containerView.
Question: What could be causing the NSTextField delegate methods to stop working after refactoring from NSView to NSViewController?
@IBOutlet weak var customeView: NSView!
var myDetailsViewController: MyDetailsViewController!
var myDetailsView: MyDetailsView!
var isViewController: Bool = true
override func windowDidLoad() {
super.windowDidLoad()
if isViewController {
myDetailsViewController = MyDetailsViewController(nibName: "MyDetailsViewController", bundle: nil)
self.customeView.addSubview(myDetailsViewController.view)
} else {
myDetailsView = MyDetailsView.createFromNib()
self.customeView.addSubview(myDetailsView!)
}
}
override func showWindow(_ sender: Any?) {
super.showWindow(nil)
window?.makeKeyAndOrderFront(nil)
}
override var windowNibName: NSNib.Name? {
return NSNib.Name("MyWindowController")
}}
class MyDetailsViewController: NSViewController {
@IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
extension MyDetailsViewController: NSTextDelegate {
func controlTextDidChange(_ obj: Notification) {
guard let textField = obj.object as? NSTextField else { return }
print("The value is ----> (MyDetailsViewController) \(textField.stringValue)")
}
}
TextField delegate is set in XIB.