i think this is simple question, but i m new to Cocoa. Where can we write -windowDidBecomeKey method for MainMenu.xib, so that when main window becomes the key the method should be invoked. Thanks.
First, go to your app delegate header file, and change something that looks like this:
#interface AppDelegate : NSObject <NSApplicationDelegate>
to this:
#interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
Then go to the implementation file, and implement the method:
- (void)windowDidBecomeKey:(NSNotification *)notification {
// do something
}
Then right click on the window's title bar in interface builder and drag the dot next to Delegate onto your app delegate.
Alternatively, you can listen to the notification. Add this to the applicationDidFinishLaunching method:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(windowDidBecomeKey:)
name:NSWindowDidBecomeKeyNotification
object:_window];
The advantage of this approach is that you can name the listener method whatever you want.
Related
I am trying to drag my buttons into the implementation but there is no prompt to create an IBAction. I had the ability to do that when the view was a class ViewController then I switched it to UIViewController I cannot add IBAction now. I was having issues with the programmatic segue when it was ViewController. The Stop Alerting button I had in there now throws errors that is why I am now trying to create a new button.
UPDATE
I tried two ways. First adding an interface and method to the existing method and header files. That did nothing. Then I tried adding them to new method and header files and that did nothing either.
#import <UIKit/UIKit.h>
#interface alertingView : UIViewController
#end
and method
#import "alertingView.h"
#implementation alertingView
- (void)viewDidLoad
{
NSLog(#"test alertingView");
}
#end
When this happen it is because the class set on your XIB (owner of the button) is not the same of the class where your are trying to release the mouse.
In my ViewController.m I have my void "Save Data":
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myDatePicker, myTextField;
-(void)saveData
{
NSArray *value = [[NSArray alloc] initWithObjects:[myTextField text],[myDatePicker date], nil];
[value writeToFile:[self getFilePath] atomically:YES];
}
And I want to use my void "Save Data" in my AppDelegate.m :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.ViewController saveData];
}
But Xcode doesn't recognize the "ViewController" neither "saveData".
I don't know if I have to #import something in my AppDelegate, please help.
How you access your viewcontroller from the app delegate will depend on how many viewcontrollers you have / where it is in your current navigation hierarchy, etc etc. You could add a property for it, or perhaps it will be your app delegate's rootViewController.
However, you'd probably be better off listening out for a notification in your viewcontroller when the app enters the background. This means that the logic you need can be entirely self contained within your viewcontroller, and your app delegate doesn't need to know anything about it.
In your viewcontroller's initialization method, you can register to receive notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
Then, implement the method:
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[self saveData];
}
And make sure you also remove yourself as an observer in your viewcontroller's dealloc method:
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}
In your "appDelegate.m" implementation file at the top do this import ->
#import "ViewController.h"
This will make the custom class ViewController visible to the appDelegate.
In order to be able to call the -(void)saveData method from another class (in our case the other class is the AppDelegate class), this method needs to be declared in the public interface. That means ->
#import "ViewController.h"
#interface ViewController ()
-(void)saveData;
#end
I'm trying to find a solution that allows me to get keydown events in a view controller.
I do not believe a view controller is part of the responder chain by default.
I would appreciate a sample of how to go about this. I have had trouble finding documentation I can understand on how to add the VC to the responder chain and get the events.
Thanks.
Miek
You can implement something like this:
-(void) globalKeyDown: (NSNotification *) notification
method in your controller class, and then just add the observer in awakeFromNib...or loadView method of your controller
- (void)awakeFromNib
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(globalKeyDown:)
name:#"my_keyEvent"
object:nil];
}
in your view class
-(void)keyDown:(NSEvent *)theEvent
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"my_keyEvent"
object:theEvent
userInfo:#{#"sender":self}];
}
NSViewController doesn't have a default way to do this. However, you can achieve this through subclassing NSView. Here is the basic idea:
If you create a view subclass, you can set your view controller as a delegate and create a delegate method that handles events.
You can declare a delegate protocol at the start of your view header.
Import your view header in the view controller header. Declare the view controller as implementing the protocol.
In your view keyDown send the event to the delegate.
Another way is to post NSNotifications in your keyDown and observe and handle the notifications in your view controller. Other ways also exist.
NSView Subclass with Delegate method explained
Here is the delegation example with an NSView subclass which declares a protocol in its header with one required method, an IBOutlet id property that conforms to the protocol. The NSView subclass calls this method to its delegate whenever it wants to. If the delegate is nil, that's fine in Cocoa. Also note, tangentially, I have added IB_Designable and IBInspectable to the view's color properties. This allows setting them in IB and requires the 10.10 SDK.
The app delegate has imported the NSView subclass in the AppDelegate.m implementation file and adopted the protocol in the AppDelegate class extension at the top of the .m file. In the #implementation section it also implements the method.
Also note in IB, I added an NSView to the window, then set its class to the custom NSView subclass in the inspector. Finally, I set its eventDelegate IBOutlet to the AppDelegate proxy in IB.
Custom NSView subclass interface
#import <Cocoa/Cocoa.h>
#protocol EventDelegatingViewDelegate <NSObject>
- (void)view:(NSView *)aView didHandleEvent:(NSEvent *)anEvent;
#end
IB_DESIGNABLE
#interface EventDelegatingView : NSView
#property IBOutlet id<EventDelegatingViewDelegate> eventDelegate;
#property IBInspectable NSColor *fillColor;
#property IBInspectable NSColor *strokeColor;
#end
Custom NSView subclass implementation
#import "EventDelegatingView.h"
#implementation EventDelegatingView
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {return YES;}
// The following two methods allow a view to accept key input events. (literally they say, YES, please send me those events if I'm the center of attention.)
- (BOOL)acceptsFirstResponder {return YES;}
- (BOOL)canBecomeKeyView {return YES;}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
[self.fillColor set];
NSRectFill(self.bounds);
[self.strokeColor set];
NSFrameRect(self.bounds);
}
// Notice these don't do anything but call the eventDelegate. I could do whatever here, but I didn't.
// The NICE thing about delgation is, the originating object stays in control of it sends to its delegate.
// However, true to the meaning of the word 'delegate', once you pass something to the delegate, you have delegated some decision making power to that delegate object and no longer have any control (if you did, you might have a bad code smell in terms of the delegation design pattern.)
- (void)mouseDown:(NSEvent *)theEvent
{
[self.eventDelegate view:self didHandleEvent:theEvent];
}
- (void)keyDown:(NSEvent *)theEvent
{
[self.eventDelegate view:self didHandleEvent:theEvent];
}
#end
App Delegate (and eventDelegate!) implementation
#import "AppDelegate.h"
// Import the view class and if there were other files that implement any protocol
#import "EventDelegatingView.h"
// Declare protocol conformance (or more accurately, not only import that protocol interface, but say you're going to implement it so the compiler can nag you if you don't)
#interface AppDelegate ()<EventDelegatingViewDelegate>
#property (weak) IBOutlet NSWindow *window;
// For the simplest demo app we don't even need this property.
#property IBOutlet EventDelegatingView *eventDelegatingView;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
// It's all right here. Receive a reference to a view and a reference to an event, then do as you like with them.
#pragma mark - EventDelegatingViewDelegate
- (void)view:(NSView *)aView didHandleEvent:(NSEvent *)anEvent
{
NSString *interestingEventNote;
switch (anEvent.type) {
case NSKeyDown:
case NSKeyUp:
{
// For simplicity we won't try to figure out the modifier keys here.
interestingEventNote = [NSString stringWithFormat:#"%# key was pressed.", anEvent.charactersIgnoringModifiers];
}
break;
case NSLeftMouseDown:
{
interestingEventNote = [NSString stringWithFormat:#"Left mouse down at point %# in window", NSStringFromPoint(anEvent.locationInWindow)];
}
break;
default:
break;
}
NSLog(#"%# %# aView=%#\n note=%#", self, NSStringFromSelector(_cmd), aView, interestingEventNote?interestingEventNote:#"Nothing worth noting");
}
#end
And that's it for the power of delegation. Basically it's callbacks of sorts and is a great way to build a class to enable it to defer something elsewhere as wanted. Moving some business logic to the right place in a fairly lazy and open and loosely coupled way.
NOTE: My code example shows using the app delegate. But the principal is the same. A view controller is little more than a delegate and you can add as much or as little as you like.
In your NSWidow (or NSWindowController) class implementation set your view controller as the first responder:
[self makeFirstResponder:yourViewControllerInstance];
You must, of course, make your NSViewController class return YES to the acceptsFirstResponder message.
I have a ViewController that imports two TableViewControllers.
I have the delegate/datasource methods executing in these subclasses, but is there anyway that the ViewController can tell when the each TableView has executed methods such as the delegate method didSelectRowAtIndexPath or do I have to add methods in each tableviewcontroller for polling if cells had been selected?
Thanks!
You can define your own notifications, e.g. "MyDidSelectRowAtIndexPathNotification", and make your main view controller an observer of this notification:
#define kMyDidSelectNotification #"MyDidSelectRowAtIndexPathNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myDidSelectAction:) name:kMyDidSelectNotification object:nil];
Then, in your implementation of tableView:didSelectRowAtIndexPath, you can simply trigger this notification for all observers:
[[NSNotificationCenter defaultCenter]
postNotificationName:kMyDidSelectNotification object:nil];
You can see here that you could pass the UITableViewCell or some other object in the notification, if you need it. Your handler for the notification (myDidSelectAction: in this case) receives an NSNotification object which would contain your object passed in the postNotification operation.
While a protocol would also work, it is more complicated to setup, in my view.
Have a look at the docs for Notification Center.
well you can create a #protocol like this:
#protocol MyChildViewControllerDelegate<NSObject>
#optional
- (void)tablView:(UITableView *)tv didSelectRowInChildViewControllerAtIndexPath:(NSIndexPath*)indexPath;
#end
now make a property of MyChildViewControllerDelegate in class ChildViewController and #synthesize it, like this:
#property(assign, nonatomic) id<MyChildViewControllerDelegate> delegate;
Now when making an instance of ChildViewController in parent classes assign the delegate by self like this:
ChildViewController *ch = [[ChildViewController alloc] initWithBlahBlah];
ch.delegate = self;
and implement the MyChildViewControllerDelegate methods.
now when you receive any UITableViewDelegate callback in ChildViewController tell your parent classes through delegates.
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)iPath
{
[delegate tablView:tView didSelectRowInChildViewControllerAtIndexPath:iPath];
}
instead of making your own MyChildViewControllerDelegate you can use apple provided UITableViewDelegate too (as you find comfort with).
Hope it helps :)
lets say I have an NSWindow Class, that has several events for mouse and trackpad movements
for example this code
IMHO, I think this should be good programming, it is similar to pointing an action of a button to its method in controller.
in MyWindow.m Class I have (which in IB I have set the window class to it)
#implementation MyWindow
- (void)swipeWithEvent:(NSEvent *)event {
NSLog(#"Track Pad Swipe Triggered");
/* I want to add something like this
Note that, Appdelegate should be existing delegate,
not a new instance, since I have variables that should be preserved*/
[AppDelegate setLabel];
}
#end
and in My AppDelegate.h I have
#interface AppDelegate : NSObject <NSApplicationDelegate>
{
IBOutlet NSTextField *label;
}
-(void)setLabel;
#end
and in my AppDelegate.m I have
-(void)setLabel
{
[label setStringValue:#"swipe is triggered"];
}
I have tried #import #class, [[... alloc] init], delegate referencing in IB (I made an object class of MyWindow - thanks to the answer of my previous question )
that latter seems the closest one, it works if both of the classes are delegates, so I could successfully call the "setLabel" action from a button in a second controller (delegate class)'s IBAction method,
but this View Events seem not communicating with the delegate's action although their code is executing.
You are sending a message to the AppDelegate class, not the instance of your AppDelegate class which is accessible from the NSApplication singleton ([NSApplication sharedApplication])
[AppDelegate setLabel];
This is wrong, to get the delegate do this:
AppDelegate* appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate];
then send the message to that instance:
[appDelegate setLabel];