Having issues passing a delegate from NSWindowController subclass to my ViewController - swift

I'm having issues with passing a custom protocol (MainWindowControllerProtocol) to the EditorViewController from the MainWindowController, which is subclass of NSWindowController. Please help.
EditorViewController.swift
extension EditorViewController: MainWindowControllerProtocol {
func didOpenFile() {
print("TODO: Open File") // never called, but it should be
}
}
class EditorViewController: NSViewController {
// - IBOutlets
#IBOutlet weak var treeOutlineView: NSOutlineView!
#IBOutlet var codeTextView: NSTextView!
#IBOutlet weak var counterTextField: NSTextField!
#IBOutlet weak var languageTextField: NSTextField!
//public var editor = Editor()
//var rootNode: Node?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
//rootNode = Path(Path.userDownloads).node
// Issue is here
if let windowController = NSApplication.shared.mainWindow?.windowController as? MainWindowController {
windowController.delegate = self
}
else {
print("Doesnt work") // prints this
}
//treeOutlineView.reloadData()
}
}
MainWindowController
public protocol MainWindowControllerProtocol {
func didOpenFile()
}
class MainWindowController: NSWindowController {
var delegate: MainWindowControllerProtocol?
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
#IBAction func openFile(_ sender: Any) {
print("In here") // this is called?
delegate?.didOpenFile() // but this never is apparently
}
}

Maybe this topic should help.
This method might return nil if the application’s nib file hasn’t
finished loading, if the receiver is not active, or if the application
is hidden.
Have you checked if NSApplication.shared.mainWindow is nil or just NSApplication.shared.mainWindow?.windowController cannot be casted to your controller class ?

Related

Two windows are presented when I start my xib only project

I am using Xcode 10.1 two create a simple single window application. The issue is that I see two windows instantiated when I run it instead of the single one I expect. Here is my code
//AppDelegate
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mainWindowController: WindowController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
print("loading")
let mainWindowController = WindowController()
mainWindowController.showWindow(self)
self.mainWindowController = mainWindowController
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
print("closed")
}
}
//WindowController.swift
import Cocoa
class WindowController: NSWindowController, NSSpeechSynthesizerDelegate {
#IBOutlet weak var textField: NSTextField!
#IBOutlet weak var speakButton: NSButton!
#IBOutlet weak var stopButton: NSButton!
override var windowNibName: String {
return "Window"
}
let speechSynth = NSSpeechSynthesizer()
var isStarted: Bool = false {
didSet {
updateButtons()
}
}
override func windowDidLoad() {
super.windowDidLoad()
viewDidLoad()
}
func viewDidLoad() {
// super.viewDidLoad()
updateButtons()
speechSynth.delegate = self
print("view load")
// Do any additional setup after loading the view.
}
#IBAction func speakIt(sender: NSButton) {
let string = textField.stringValue
if string.isEmpty {
print("String is empty")
}
else {
print(string)
speechSynth.startSpeaking(string)
isStarted = true
}
}
#IBAction func stopIt(sender: NSButton) {
speechSynth.stopSpeaking()
isStarted = false
}
func updateButtons() {
if isStarted {
speakButton.isEnabled = false
stopButton.isEnabled = true
} else {
stopButton.isEnabled = false
speakButton.isEnabled = true
}
}
func speechSynthesizer(_ sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) {
isStarted = false
}
}
My Xib has the option checked "Visible at launch". If I uncheck it, I see no window.
Basically, I am attempting a program from the book "Cocoa Programming for OSX". However, the book is obsolete. But I am trying to find my way through new Xcode and Swift. Any help?
Also a point worth noting is that only one window is functional, the second window IBOutlets and IBAction are not connected. So nothing happens in the second window.
I can't figure out why is this happening?

Is it possible to modify the properties of a subclass from a parent class in Swift 4?

Via a method or closure, perhaps?
I created a subclass view controller of my superclass/parent view controller and placed labels with placeholder text in that subclass view controller.
I want to set the labels' values to blank strings from the superclass/parent view controller, or, specifically, from an IBAction function that causes the subclass view controller to appear.
Here is the code, first from the parent class, then from the subclass...
'''
class ViewController: UIViewController {
#IBAction func leavingView(){
self.EntryViewController.entryDateLabel.text = ""
self.EntryViewController.entryLabel.text = ""
self.dismiss(animated: true, completion: nil)
}
'''
then from the subclass...
'''
class EntryViewController: ViewController {
#IBOutlet var entryDateLabel: UILabel!
#IBOutlet var entryLabel: UILabel!
}
'''
I have come up with 2 solutions to this problem, without having the parent view controller know about its subclass.
In the first example the parent sets properties on itself that the child listens to (via the didSet method, it then updates its view accordingly. However, this isn't ideal because the entryDate and entry string fields are useless on their own, almost redundant in the parent.
class ParentViewController: UIViewController {
var entryDate: String?
var entry: String?
#IBAction func leavingView(){
self.entryDate = ""
self.entry = ""
self.dismiss(animated: true, completion: nil)
}
}
class ChildViewController: ParentViewController {
#IBOutlet var entryDateLabel: UILabel!
#IBOutlet var entryLabel: UILabel!
override var entryDate: String? {
didSet {
guard isViewLoaded else {
return
}
entryDateLabel.text = entryDate
}
}
override var entry: String? {
didSet {
guard isViewLoaded else {
return
}
entryLabel.text = entry
}
}
}
In my opinion, the second solution is clearer and keeps implementation details more separate because you're using instructions or events to notify the child view controllers.
class ParentViewController: UIViewController {
#IBAction func leavingView(){
self.dismiss(animated: true, completion: didLeaveView)
}
func didLeaveView() { }
}
class ChildViewController: ParentViewController {
#IBOutlet var entryDateLabel: UILabel!
#IBOutlet var entryLabel: UILabel!
override func didLeaveView() {
entryDateLabel.text = ""
entryLabel.text = ""
}
}
Since your requirement is not that much clear I have created a demo for you and into that demo I have added child ContainerViewController into parent ViewController and from that parent view controller you can change UILabel text when you click on UIButton of parent ViewController and code will be for ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnFromParentViewTapped(_ sender: Any) {
//Here get the child of your parent view controller
if let containerView = self.children[0] as? ContainerViewController {
containerView.lblContainer.text = ""
}
}
}
and ContainerViewController code will be:
class ContainerViewController: UIViewController {
#IBOutlet weak var lblContainer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Don't need to add much here because you are accessing it from parent view.
And your result will be:
As you can see when I click on button which title says Change Container label text the label text from ContainerViewController set to empty string.
For more info check THIS demo project.

How to set NSButton.isEnabled from subclassed NSTextField

I'm very new to Swift MacOS programming and have been learning by writing small test applications.
The aim of this application is to enable the pushbutton when the 2nd textfield has the focus, and disable it when it is not focused.
I have found that by subclassing the NSTextField I can override becomeFirstResponder() however don't know how to set the button to be disabled from the subclass.
ViewController:
class ViewController: NSViewController {
#IBOutlet public weak var pushButton: NSButton!
#IBOutlet weak var textField3: NSTextField!
#IBOutlet weak var textField2: GSTextField!
#IBOutlet weak var textField1: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func chgButton(onoff: Bool){
pushButton.isEnabled = onoff
}
}
// When the field completes editing make the pushbutton disabled.
extension ViewController: NSTextFieldDelegate {
override func controlTextDidEndEditing(_ obj: Notification) {
print("did end")
chgButton(onoff: false)
}
}
GSTextField.Swift
class GSTextField: NSTextField {
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
////*** I need to set the button to be enabled here
return super.becomeFirstResponder()
}
}
Your NSTextField subclass needs to be able to communicate with the pushButton. The easiest way to do this is to pass a reference to the pushButton to your text field and then update the push button from there.
Update your ViewController like this:
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
textField2.pushButton = pushButton
// Do any additional setup after loading the view.
}
And your GSTextField like this:
class GSTextField: NSTextField {
weak var pushButton: NSButton?
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
pushButton?.isEnabled = true
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
pushButton?.isEnabled = false
return super.resignFirstResponder()
}
}
It should be noted that while this works fine in this toy example, this is a sub-optimal solution to this problem because it tightly couples the pushButton and the GSTextField. A better solution would be to use delegation to communicate the focus changes to the ViewController, and let the ViewController handle the updates.
Your GSTextField would look like this:
protocol FocusObservable: class {
func didGainFocus(sender: Any)
func didLoseFocus(sender: Any)
}
class GSTextField: NSTextField {
weak var focusDelegate: FocusObservable?
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
focusDelegate?.didGainFocus(sender: self)
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
focusDelegate?.didLoseFocus(sender: self)
return super.resignFirstResponder()
}
}
And then you would add protocol conformance to the ViewController:
extension ViewController: FocusObservable {
func didGainFocus(sender: Any) {
pushButton.isEnabled = true
}
func didLoseFocus(sender: Any) {
pushButton.isEnabled = false
}
}
and set the focusDelegate of the text field:
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
textField2.focusDelegate = self
// Do any additional setup after loading the view.
}

Error while assigning self to tableview datasource

This is the error Xcode outputs
Unexpectedly found nil while unwrapping an Optional value
I have a viewcontroller that has a tableview and a few buttons; the buttons allow me to insert or remove data. It seems that when I click on Add (which brings up a new viewcontroller via segue as a sheet) the app crashes with the error above. Clicking on remove doesn't have this affect. So it has to do with something regarding the new viewcontroller as a guess. The console doesn't go further into the error other than printing out (lldb)
Here's my code
override func viewDidLoad() {
super.viewDidLoad()
alarmTableView.dataSource = self //error occurs here
alarmTableView.delegate = self //if i remove the above line if will occur here too.
}
My Viewcontroller which the above viewDidLoad func is embedded lists the protocols I need
class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
#IBOutlet weak var addAlarm: NSButton!
#IBOutlet weak var resetDataButton: NSButton!
#IBOutlet var alarmArrayController: NSArrayController!
#IBOutlet weak var alarmTableView: NSTableView!
#IBOutlet weak var deleteAll: NSButton!
#objc let moc: NSManagedObjectContext
required init?(coder: NSCoder) {
self.moc = CoreDataHandler.getContext()
super.init(coder: coder)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
let destinationController = segue.destinationController as! AddAlarmViewController
//pass data to next controller here
}
#IBAction func deleteAllAction(_ sender: Any) {
if (alarmTableView.selectedRow >= 0) {
if (CoreDataHandler.deleteAllObjectsInEntity(entityName: "Alarm")) {
//remove from nsarray controller
for object in alarmArrayController.arrangedObjects as! [Alarm] {
print(object)
alarmArrayController.removeObject(object)
}
alarmTableView.reloadData()
}
}
else {
printInfo(str: "There are no alarms to delete")
}
}
/* Response to the remove alarm button - It removes a selected alarm object from the table */
#IBAction func resetDataAction(_ sender: Any) {
if (alarmTableView.selectedRow >= 0) {
let selectedAlarm = self.alarmArrayController.selectedObjects.first as! Alarm
alarmArrayController.remove(atArrangedObjectIndex: alarmTableView.selectedRow)
CoreDataHandler.deleteObjectInEntity(entityName: "Alarm", obj: selectedAlarm)
alarmTableView.reloadData()
}
else {
//will need a warning or play a sound.
printInfo(str: "Please select an alarm")
}
}
override func viewDidLoad() {
super.viewDidLoad()
printInfo(str: "viewdidload")
print(alarmTableView)
if (alarmTableView != nil) {
printInfo(str: "AlarmTableView Is initialised")
alarmTableView.dataSource = self
alarmTableView.delegate = self
}
else {
printInfo(str: "AlarmTableView is not initialised")
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func printInfo(str: String) {
print("ViewController: \(str)")
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 100.0
}
}
class AddAlarmViewController: ViewController {
#IBOutlet weak var closeButton: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
printClassInfo(str: "viewDidLoad")
CoreDataHandler.saveTestData()
}
#IBAction func closeButtonAction(_ sender: Any) {
self.dismissViewController(self)
}
func printClassInfo(str: String) {
print("AddAlarmViewController \(str)")
}
}
If I remove the lines where the error occurs the app run fine. But I want to override the delegate and datasource and use the functions to further customise the table. I'm also using Cocoa Bindings.
Why am I getting this error?
Update
I haven't solved it yet, but i placed a couple of print statements in my viewDidLoad function. It seems that when the app is first loaded, the table view is initialised. But after when I clicked on the Add button, the table view is then set to nil for some odd reason, as if another table view has been initialised. However the data is still visible
Problem:
class AddAlarmViewController: ViewController {
//...
override func viewDidLoad() {
super.viewDidLoad()
//...
}
}
Your AddAlarmViewController is a subclass of ViewController instead of NSViewController.
In AddAlarmViewController's viewDidLoad you call super.viewDidLoad() which basically calls ViewController's viewDidLoad.
But... in this case ViewController is a new instance as the super class of AddAlarmViewController and none of it's properties are initialized.
Whatever it be, it's probably not what you want.
Solution:
class AddAlarmViewController: NSViewController {
//... rest as it is
}

Delegate Method is not called in Swift?

I want to pass a Bool value from on view controller to another without the help of segues. So i referred & got Delegates.
I have applied delegates in my App. But the Delegate method is not being called. I don't know where i am making the mistake.
So Please help me.
MainViewController
class MainViewController: UIViewController, WriteValueBackDelegate {
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
Second View Controller
class LoginController: UIViewController {
#IBOutlet weak var LoginLabel: UILabel!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var pwd: UITextField!
var LoggedInL :Bool?
var mydelegate: WriteValueBackDelegate?
override func viewDidLoad() {
super.viewDidLoad() }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func onSubmit(sender: AnyObject) {
Alamofire.request(.GET, "http://www.jive.com/index.php/capp/user_verification/\(email.text)/\(pwd.text)")
.responseJSON { (_, _, data, _) in
println(data)
let json = JSON(data!)
let name = json["first_name"].stringValue
let status = json["valid_status"].intValue
println(status)
var e = self.email.text
println(e)
self.LoginLabel.text = "Hey \(name)!"
if status == 1{
println("Correect")
self.LoggedInL = true
self.mydelegate?.writeValueBack(true)
}else {
self.LoggedInL = false
println("Error")
}
}
navigationController!.popViewControllerAnimated(true)
}
}
protocol WriteValueBackDelegate {
func writeValueBack(value: Bool)
}
you didn't initialize the delegate, and no need to, delegates are usually for async callbacks. do that instead:
class MainViewController: UIViewController {
static var sharedInstace : MainViewController?;
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
MainViewController.sharedInstace = self; //this is better from init function
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
}
in login view controller
MainViewController.sharedInstance?.writeValueBack(true)
In MainViewControlleryou need a reference of the LoginController instance maybe with an IBOutlet and then set the delegate in viewDidLoad
#IBOutlet weak var loginController : LoginController!
override func viewDidLoad() {
super.viewDidLoad()
loginController.mydelegate = self
}