NSInvalidArgumentException reason keyboardWasHidden? - cocoa-touch

What's wrong here?
- (IBAction)textFieldDidEndEditing:(id)sender
{
if(!_isEditing )
return;
UITextField* textField = (UITextField*)sender;
NSString* newValue = [textField text];
UITableViewCell* cell = [self GetCellFromTextField:textField];
NSString* fieldName =[(UILabel*)[self GetLabelHeaderFromCell:cell] text];
NSIndexPath* indexPath= [self GetIndexPathForCell:cell];
[PersonalSection SetFieldValue:newValue AndFieldName:fieldName UsingIndexPath:indexPath AndPersonalInformation:self.personalInfoInUse];
_trackingEditTextField=nil;
[fieldName release];
_isEditing = FALSE;
}
- (IBAction)textFieldDidBeginEditing:(id)sender
{
_trackingEditTextField=(UITextField*)sender;
}
-(IBAction)textFieldDidChange
{
_isEditing=YES;
self.navigationItem.rightBarButtonItem = saveButton;
self.navigationItem.leftBarButtonItem = cancelButton;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[_trackingEditTextField resignFirstResponder];
return NO;
}
-(void)KeyboardDidShow:(NSNotification*) notification
{
if ( keyboardShown )
return;
CGRect frame = tableView.frame;
frame.size.height -= 165;
tableView.frame = frame;
[tableView scrollToRowAtIndexPath:[self GetIndexPathForTextView:_trackingEditTextField] atScrollPosition:0 animated:YES];
keyboardShown = YES;
}
- (void)keyboardWasHidden:(NSNotification *)notification {
if ( keyboardShown ) {
CGRect frame = tableView.frame;
frame.size.height += 165;
tableView.frame = frame;
keyboardShown = NO;
}
}
The exception fires when trying to resign first responder (i.e. when i click the 'done' button on the keyboard) but the keyboard is still showing and it did not enter keyboardWasHidden yet, which is the receiver of UIKeyboardWillHideNotification

I was listening to the notification through the following line of code
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(keyboardWasHidden::) name:UIKeyboardWillHideNotification object:nil];
so it was a small mistake,
The selector "keyboardWasHidden::" should have been "keyboardWasHidden:"
hope it's useful for anybody.

Related

Is there any notification that gets sent when the Keyboard changes (like from NumberPad to Default)

I am trying to figure out how I can get notified when the keyboard changes. What I am trying to do is add a DONE button to keyboard of type 4 & 5 (NumberPad and PhonePad), everything is working fine, except when I transition from a TextField using a Default KB type, The notification that the KeyboardDidAppear isn't being fired.
Here is what I got:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
}
Then I added a Property for the current KB type and the current TextField being edited:
#pragma mark - Delegate Methods
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
self.currentKBType = textField.keyboardType;
self.curTextField = textField;
return YES;
}
I then make a decision on whether or not to add that DONE button based on the current KB type:
- (void)keyboardDidShow:(NSNotification *)note {
if (self.currentKBType == 4 || self.currentKBType == 5) {
[self addButtonToKeyboard];
}
}
Problem is that the notification fires when the keyboard is displayed, but not when it changes (transitions from one TextField to another that specifies a different KB type.
Any suggestions? Am I missing something?
Got this figured out. Took a little logic, but it works flawlessly. Here is what I did:
Added private properties for:
#property (nonatomic) UIKeyboardType currentKBType;
#property(nonatomic,strong) UITextField *curTextField;
#property(nonatomic,strong) UIButton *doneButton;
#property(nonatomic) BOOL doneButtonDisplayed;
Then added the following logic in the both the TextField delegate method:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
self.currentKBType = textField.keyboardType;
if (textField.keyboardType == 4 || textField.keyboardType == 5) {
if (!doneButtonDisplayed) {
[self addButtonToKeyboard];
}
} else {
if (doneButtonDisplayed) {
[self removeButtonFromKeyboard];
}
}
self.curTextField = textField;
return YES;
}
And in the KeyboardDidShowNotification that I signed the VC up for in the viewDidLoad:
- (void)keyboardDidShow:(NSNotification *)note {
if (self.currentKBType == 4 || self.currentKBType == 5) {
if (!doneButtonDisplayed) {
[self addButtonToKeyboard];
}
} else {
if (doneButtonDisplayed) {
[self removeButtonFromKeyboard];
}
}
}
And the two methods referenced in these methods:
- (void)addButtonToKeyboard {
// create custom button
doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:#"DoneNormal.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneHL.png"] forState:UIControlStateHighlighted];
[doneButton addTarget:self action:#selector(resignKeyboard) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
if ([[[UIApplication sharedApplication] windows] count] > 1) {
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES) {
[keyboard addSubview:doneButton];
self.doneButtonDisplayed = YES;
}
}
}
}
- (void)removeButtonFromKeyboard {
[doneButton removeFromSuperview];
self.doneButtonDisplayed = NO;
}
And finally, the resignKeyboard method that is called whenever the Done button is touched:
-(void)resignKeyboard {
[self.curTextField resignFirstResponder];
self.doneButtonDisplayed = NO;
}
This will add that Done button whenever a NumberPad or PhonePad type keyboard is displayed and remove it (only when it has been added) from the other keyboard types.
Tested and works great.

UIButton disappears when my application returns from running in the background

I have a small project that contains a few UITextFields with a number keypad. When the keyboard is displayed I'm adding a button as a subview for the user to dismiss the keyboard.
However, if the keyboard is active and I close the application, the button I've added will disappear upon relaunching the app. (The app stays inactive, through multitasking, and therefore not quit completely.)
This is the code im using to add the button (my "done" button configured in the xib).
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow)name:UIKeyboardWillShowNotification object:nil];
[super viewDidLoad];
}
- (void)keyboardWillShow{
[[NSNotificationCenter defaultCenter] removeObserver:self];
// We must perform on delay (schedules on next run loop pass) for the keyboard subviews to be present.
[self performSelector:#selector(addHideKeyboardButtonToKeyboard) withObject:nil afterDelay:0];
}
- (void)addHideKeyboardButtonToKeyboard{
// Locate non-UIWindow.
doneButton.hidden=NO;
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
if (!keyboardWindow) return;
// Locate UIKeyboard.
UIView *foundKeyboard = nil;
for (UIView __strong *possibleKeyboard in [keyboardWindow subviews]) {
// iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
if ([[possibleKeyboard description] hasPrefix:#"<UIPeripheralHostView"]) {
possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
}
if ([[possibleKeyboard description] hasPrefix:#"<UIKeyboard"]) {
foundKeyboard = possibleKeyboard;
break;
}
}
if (foundKeyboard) {
[doneButton setImage:[UIImage imageNamed:#"doneupHeb.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"donedownHeb.png"] forState:UIControlStateHighlighted];
doneButton.frame = CGRectMake(-1, 163, 106, 53);
[foundKeyboard addSubview:doneButton];
// Add the button to foundKeyboard.
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[prime resignFirstResponder];
[MothlyReturn resignFirstResponder];
[doneButton removeFromSuperview];
doneButton = nil;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
textField.delegate=self;
//editingField = textField;
if ([prime isFirstResponder]||[MothlyReturn isFirstResponder]){
scroll.contentOffset = CGPointMake(0, 166 );
}
// if ([YearCycle isFirstResponder]){
// scroll.contentOffset = CGPointMake(0, 200);
}
- (IBAction)closeNumpad:(id)sender{
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[prime resignFirstResponder];
[MothlyReturn resignFirstResponder];
scroll.contentOffset = CGPointMake(0, 0);
doneButton.hidden=YES;
}
i fixed the problem with a little help from other questions in the website - for all of you that have or will have the problem - this is the code:
Please note: the button himself are designed in the xib file and not in the code.
the .h file:
BOOL firstTime;
BOOL add;
BOOL keyboardOpened;
IBOutlet UIButton *doneButton;
the .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
firstTime = TRUE;
add = TRUE;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; // Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
// [[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)addButtonToKeyboard {
// create custom button
/* UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:#"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown.png"] forState:UIControlStateHighlighted];
doneButton.tag = 3;
[doneButton addTarget:self action:#selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];*/
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[keyboard description] hasPrefix:#"<UIPeripheralHostView"] == YES && add){
doneButton.frame = CGRectMake(-1, 163, 106, 53);
[keyboard addSubview:doneButton];
}
}
}
- (void)removeButtonFromKeyboard
{
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, remove the button
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES) [[keyboard viewWithTag:3] removeFromSuperview];
}
}
- (IBAction)doneButton:(id)sender {
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[ageOfCeo resignFirstResponder];
[YearofBusiness resignFirstResponder];
scroll.contentOffset = CGPointMake(0, 0);
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
[self removeButtonFromKeyboard];
firstTime = TRUE;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([ageOfCeo isFirstResponder]||[YearofBusiness isFirstResponder]){
scroll.contentOffset = CGPointMake(0, 166 );
}
// firstResponder = textField;
}
- (void)keyboardDidShow:(id)sender
{
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
NSLog(#"%#",[[UIDevice currentDevice] model]);
[self addButtonToKeyboard];
keyboardOpened = TRUE;
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
[self removeButtonFromKeyboard];
keyboardOpened = FALSE;
}
}
i think your problem because you are removing the observer in the - (void)keyboardWillShow .. try to put this line [[NSNotificationCenter defaultCenter] removeObserver:self]; in the -(void)viewDidUnload

how to remove prev next button from virtual keyboard IOS

i have use a UIWebview in IOS 5. I try to set contenteditable="true" to make uiwebview editable.
The screenshoot of my app is similar to an image in this link How do you remove the Next and Prev buttons from virtual keyboard in Sencha Touch / Phonegap application,
my problem is i want to remove this prev & next button from the keyboard, but i dont know how. Can some body help me?
thank you
This is an old answer and is no longer working on iOS 9. For an updated solution, see my answer here.
It is a gray-area, but certainly possible.
See here: http://ios-blog.co.uk/iphone-development-tutorials/rich-text-editing-a-simple-start-part-1/
Register for notification on keyboard showing:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
Then:
- (void)keyboardWillShow:(NSNotification *)note {
[self performSelector:#selector(removeBar) withObject:nil afterDelay:0];
}
- (void)removeBar {
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
// Locate UIWebFormView.
for (UIView *possibleFormView in [keyboardWindow subviews]) {
// iOS 5 sticks the UIWebFormView inside a UIPeripheralHostView.
if ([[possibleFormView description] rangeOfString:#"UIPeripheralHostView"].location != NSNotFound) {
for (UIView *subviewWhichIsPossibleFormView in [possibleFormView subviews]) {
if ([[subviewWhichIsPossibleFormView description] rangeOfString:#"UIWebFormAccessory"].location != NSNotFound) {
[subviewWhichIsPossibleFormView removeFromSuperview];
}
}
}
}
}
Remove the empty area.
- (void)removeBar {
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
// Locate UIWebFormView
for (UIView *possibleFormView in [keyboardWindow subviews]) {
if ([[possibleFormView description] hasPrefix:#"<UIPeripheralHostView"]) {
for (UIView* peripheralView in [possibleFormView subviews]) {
// hides the backdrop (iOS 7)
if ([[peripheralView description] hasPrefix:#"<UIKBInputBackdropView"]) {
//skip the keyboard background....hide only the toolbar background
if ([peripheralView frame].origin.y == 0){
[[peripheralView layer] setOpacity:0.0];
}
}
// hides the accessory bar
if ([[peripheralView description] hasPrefix:#"<UIWebFormAccessory"]) {
// remove the extra scroll space for the form accessory bar
UIScrollView *webScroll;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) {
webScroll = [[self webView] scrollView];
} else {
webScroll = [[[self webView] subviews] lastObject];
}
CGRect newFrame = webScroll.frame;
newFrame.size.height += peripheralView.frame.size.height;
webScroll.frame = newFrame;
// remove the form accessory bar
[peripheralView removeFromSuperview];
}
// hides the thin grey line used to adorn the bar (iOS 6)
if ([[peripheralView description] hasPrefix:#"<UIImageView"]) {
[[peripheralView layer] setOpacity:0.0];
}
}
}
}
}
It's the inputAccessoryView for UIWebBrowserView (inner UIWebView), you can hack it.
Here is an example: https://gist.github.com/bjhomer/2048571
I found the solution for iOS 8. You can check it here:
-(void) removeKeyboard {
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual : [UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
// Locate UIWebFormView.
for (UIView *possibleFormView in [keyboardWindow subviews]) {
if ([[possibleFormView description] hasPrefix : #"<UIInputSetContainerView"]) {
for (UIView* peripheralView in possibleFormView.subviews) {
for (UIView* peripheralView_sub in peripheralView.subviews) {
// hides the backdrop (iOS 8)
if ([[peripheralView_sub description] hasPrefix : #"<UIKBInputBackdropView"] && peripheralView_sub.frame.size.height == 44) {
[[peripheralView_sub layer] setOpacity : 0.0];
}
// hides the accessory bar
if ([[peripheralView_sub description] hasPrefix : #"<UIWebFormAccessory"]) {
for (UIView* UIInputViewContent_sub in peripheralView_sub.subviews) {
CGRect frame1 = UIInputViewContent_sub.frame;
frame1.size.height = 0;
peripheralView_sub.frame = frame1;
UIInputViewContent_sub.frame = frame1;
[[peripheralView_sub layer] setOpacity : 0.0];
}
CGRect viewBounds = peripheralView_sub.frame;
viewBounds.size.height = 0;
peripheralView_sub.frame = viewBounds;
}
}
}
}
}
}
You may try and improve this. try call this function inside Your UIKeyboardDidShowNotification event handler.
Hope this helps...
This is the level of views in accessory:
(UIWebFormAccessory) -> (UIToolbar) -> (UIImageView,UIToolbarButton,UIToolbarButton)

NSStatusItem right click menu

I'm working on a status bar app that has a left and right click. I've got the start of this working by following the tips from other posts but I'm not sure how to go about showing a menu on right click.
I use a subclassed NSView as the custom view of my NSStatusItem and have the right and left clicks executing different functions:
- (void)mouseDown:(NSEvent *)theEvent{
[super mouseDown:theEvent];
if ([theEvent modifierFlags] & NSCommandKeyMask){
[self.target performSelectorOnMainThread:self.rightAction withObject:nil waitUntilDone:NO];
}else{
[self.target performSelectorOnMainThread:self.action withObject:nil waitUntilDone:NO];
}
}
- (void)rightMouseDown:(NSEvent *)theEvent{
[super rightMouseDown:theEvent];
[self.target performSelectorOnMainThread:self.rightAction withObject:nil waitUntilDone:NO];
}
How can I show a menu on right click, the same way the standard NSStatusItem does on left click?
NSStatusItem popUpStatusItemMenu: did the trick. I am calling it from my right click action and passing in the menu I want to show and it's showing it! This is not what I would have expected this function to do, but it's working.
Here's the important parts of what my code looks like:
- (void)showMenu{
// check if we are showing the highlighted state of the custom status item view
if(self.statusItemView.clicked){
// show the right click menu
[self.statusItem popUpStatusItemMenu:self.rightClickMenu];
}
}
// menu delegate method to unhighlight the custom status bar item view
- (void)menuDidClose:(NSMenu *)menu{
[self.statusItemView setHighlightState:NO];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
// setup custom view that implements mouseDown: and rightMouseDown:
self.statusItemView = [[ISStatusItemView alloc] init];
self.statusItemView.image = [NSImage imageNamed:#"menu.png"];
self.statusItemView.alternateImage = [NSImage imageNamed:#"menu_alt.png"];
self.statusItemView.target = self;
self.statusItemView.action = #selector(mainAction);
self.statusItemView.rightAction = #selector(showMenu);
// set menu delegate
[self.rightClickMenu setDelegate:self];
// use the custom view in the status bar item
self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
[self.statusItem setView:self.statusItemView];
}
Here is the implementation for the custom view:
#implementation ISStatusItemView
#synthesize image = _image;
#synthesize alternateImage = _alternateImage;
#synthesize clicked = _clicked;
#synthesize action = _action;
#synthesize rightAction = _rightAction;
#synthesize target = _target;
- (void)setHighlightState:(BOOL)state{
if(self.clicked != state){
self.clicked = state;
[self setNeedsDisplay:YES];
}
}
- (void)drawImage:(NSImage *)aImage centeredInRect:(NSRect)aRect{
NSRect imageRect = NSMakeRect((CGFloat)round(aRect.size.width*0.5f-aImage.size.width*0.5f),
(CGFloat)round(aRect.size.height*0.5f-aImage.size.height*0.5f),
aImage.size.width,
aImage.size.height);
[aImage drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
}
- (void)drawRect:(NSRect)rect{
if(self.clicked){
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
if(self.alternateImage){
[self drawImage:self.alternateImage centeredInRect:rect];
}else if(self.image){
[self drawImage:self.image centeredInRect:rect];
}
}else if(self.image){
[self drawImage:self.image centeredInRect:rect];
}
}
- (void)mouseDown:(NSEvent *)theEvent{
[super mouseDown:theEvent];
[self setHighlightState:!self.clicked];
if ([theEvent modifierFlags] & NSCommandKeyMask){
[self.target performSelectorOnMainThread:self.rightAction withObject:nil waitUntilDone:NO];
}else{
[self.target performSelectorOnMainThread:self.action withObject:nil waitUntilDone:NO];
}
}
- (void)rightMouseDown:(NSEvent *)theEvent{
[super rightMouseDown:theEvent];
[self setHighlightState:!self.clicked];
[self.target performSelectorOnMainThread:self.rightAction withObject:nil waitUntilDone:NO];
}
- (void)dealloc{
self.target = nil;
self.action = nil;
self.rightAction = nil;
[super dealloc];
}
#end
One option is to just fake the left mouse down:
- (void)rightMouseDown: (NSEvent *)event {
NSEvent * newEvent;
newEvent = [NSEvent mouseEventWithType:NSLeftMouseDown
location:[event locationInWindow]
modifierFlags:[event modifierFlags]
timestamp:CFAbsoluteTimeGetCurrent()
windowNumber:[event windowNumber]
context:[event context]
eventNumber:[event eventNumber]
clickCount:[event clickCount]
pressure:[event pressure]];
[self mouseDown:newEvent];
}
Added little something for when you need title in your view
- (void)drawRect:(NSRect)rect{
if(self.clicked){
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
if(self.alternateImage){
[self drawImage:self.alternateImage centeredInRect:rect];
}else if(self.image){
[self drawImage:self.image centeredInRect:rect];
} else {
[self drawTitleInRect:rect];
}
} else if(self.image){
[self drawImage:self.image centeredInRect:rect];
} else {
[self drawTitleInRect:rect];
}
}
-(void)drawTitleInRect:(CGRect)rect
{
CGSize size = [_title sizeWithAttributes:nil];
CGRect newRect = CGRectMake(MAX((rect.size.width - size.width)/2.f,0.f),
MAX((rect.size.height - size.height)/2.f,0.f),
size.width,
size.height);
NSDictionary *attributes = #{NSForegroundColorAttributeName : self.clicked?[NSColor highlightColor]:[NSColor textColor]
};
[_title drawInRect:newRect withAttributes:attributes];
}
- (void)statusItemAction {
NSEvent *event = NSApp.currentEvent;
if (event.type == NSEventTypeRightMouseDown || (event.modifierFlags & NSEventModifierFlagControl)) {
[self toggleMenu];
} else {
[self togglePopOver];
}
}

Making a window pop in and out of the edge of the screen

I'm trying to re-write an application I have for Windows in Objective-C for my Mac, and I want to be able to do something like Mac's hot corners. If I move my mouse to the left side of the screen it will make a window visible, if I move it outside of the window location the window will hide again. (window would be pushed up to the left side of screen).
Does anyone know where I can find some demo code (or reference) on how to do this, or at least how to tell where the mouse is at, even if the current application is not on top. (not sure how to word this, too used to Windows world).
Thank you
-Brad
You're going to want to implement an invisible window on the edge of the screen with the window order set so it's always on top. Then, you can listen for mouse-moved events in this window.
To set the window to be invisible and on top, make a window subclass use calls like:
[self setBackgroundColor:[NSColor clearColor]];
[self setExcludedFromWindowsMenu:YES];
[self setCanHide:NO];
[self setLevel:NSScreenSaverWindowLevel];
[self setAlphaValue:0.0f];
[self setOpaque:NO];
[self orderFrontRegardless];
then, to turn on mouse moved events,
[self setAcceptsMouseMovedEvents:YES];
will cause the window to get calls to:
- (void)mouseMoved:(NSEvent *)theEvent
{
NSLog(#"mouse moved into invisible window.");
}
So hopefully that's enough to give you a start.
-Ken
Here's AutoHidingWindow - a subclass of SlidingWindow which pops up when the mouse hits the edge of the screen. Feedback welcome.
#interface ActivationWindow : NSWindow
{
AutoHidingWindow *_activationDelegate;
NSTrackingArea *_trackingArea;
}
- (ActivationWindow*)initWithDelegate:(AutoHidingWindow*)activationDelegate;
#property (assign) AutoHidingWindow *activationDelegate;
#property (retain) NSTrackingArea *trackingArea;
- (void)adjustWindowFrame;
- (void)adjustTrackingArea;
#end
#interface AutoHidingWindow ()
- (void)autoShow;
- (void)autoHide;
#end
#implementation AutoHidingWindow
- (id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag
{
if ((self = [super initWithContentRect:contentRect
styleMask:NSBorderlessWindowMask
backing:backingType
defer:flag])) {
_activationWindow = [[ActivationWindow alloc] initWithDelegate:self];
}
return self;
}
#synthesize activationWindow = _activationWindow;
- (void)dealloc
{
[_activationWindow release], _activationWindow = nil;
[super dealloc];
}
- (void)makeKeyAndOrderFront:(id)sender
{
[super makeKeyAndOrderFront:sender];
}
- (void)autoShow
{
[self makeKeyAndOrderFront:self];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(autoHide) object:nil];
[self performSelector:#selector(autoHide) withObject:nil afterDelay:2];
}
- (void)autoHide
{
NSPoint mouseLocation = [NSEvent mouseLocation];
NSRect windowFrame = [self frame];
if (NSPointInRect(mouseLocation, windowFrame)) {
[self performSelector:#selector(autoHide) withObject:nil afterDelay:2];
}
else {
[self orderOut:self];
}
}
#end
#implementation ActivationWindow
- (ActivationWindow*)initWithDelegate:(AutoHidingWindow*)activationDelegate
{
if ((self = [super initWithContentRect:[[NSScreen mainScreen] frame]
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO]) != nil) {
_activationDelegate = activationDelegate;
[self setBackgroundColor:[NSColor clearColor]];
[self setExcludedFromWindowsMenu:YES];
[self setCanHide:NO];
[self setHasShadow:NO];
[self setLevel:NSScreenSaverWindowLevel];
[self setAlphaValue:0.0];
[self setIgnoresMouseEvents:YES];
[self setOpaque:NO];
[self orderFrontRegardless];
[self adjustWindowFrame];
[self.activationDelegate addObserver:self
forKeyPath:#"slidingEdge"
options:0
context:#"slidingEdge"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(screenParametersChanged:)
name:NSApplicationDidChangeScreenParametersNotification
object:nil];
}
return self;
}
#synthesize activationDelegate = _activationDelegate;
#synthesize trackingArea = _trackingArea;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([#"slidingEdge" isEqual:context]) {
[self adjustTrackingArea];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.activationDelegate removeObserver:self forKeyPath:#"slidingEdge"];
_activationDelegate = nil;
[_trackingArea release], _trackingArea = nil;
[super dealloc];
}
- (void)screenParametersChanged:(NSNotification *)notification
{
[self adjustWindowFrame];
}
- (void)adjustWindowFrame
{
NSScreen *mainScreen = [NSScreen mainScreen];
CGFloat menuBarHeight = [NSMenuView menuBarHeight];
NSRect windowFrame = [mainScreen frame];
windowFrame.size.height -= menuBarHeight;
[self setFrame:windowFrame display:NO];
[self adjustTrackingArea];
}
- (void)adjustTrackingArea
{
NSView *contentView = [self contentView];
NSRect trackingRect = contentView.bounds;
CGRectEdge slidingEdge = self.activationDelegate.slidingEdge;
CGFloat trackingRectSize = 2.0;
switch (slidingEdge) {
case CGRectMaxXEdge:
trackingRect.origin.x = trackingRect.origin.x + trackingRect.size.width - trackingRectSize;
trackingRect.size.width = trackingRectSize;
break;
case CGRectMaxYEdge:
trackingRect.origin.y = trackingRect.origin.y + trackingRect.size.height - trackingRectSize;
trackingRect.size.height = trackingRectSize;
break;
case CGRectMinXEdge:
trackingRect.origin.x = 0;
trackingRect.size.width = trackingRectSize;
break;
case CGRectMinYEdge:
default:
trackingRect.origin.y = 0;
trackingRect.size.height = trackingRectSize;
}
NSTrackingAreaOptions options =
NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
NSTrackingActiveAlways |
NSTrackingEnabledDuringMouseDrag;
NSTrackingArea *trackingArea = self.trackingArea;
if (trackingArea != nil) {
[contentView removeTrackingArea:trackingArea];
}
trackingArea = [[NSTrackingArea alloc] initWithRect:trackingRect
options:options
owner:self
userInfo:nil];
[contentView addTrackingArea:trackingArea];
self.trackingArea = [trackingArea autorelease];
}
- (void)mouseEntered:(NSEvent *)theEvent
{
[self.activationDelegate autoShow];
}
- (void)mouseMoved:(NSEvent *)theEvent
{
[self.activationDelegate autoShow];
}
- (void)mouseExited:(NSEvent *)theEvent
{
}
#end
you may look how we did it in the Visor project:
http://github.com/binaryage/visor/blob/master/src/Visor.m#L1025-1063
Here's what I came up with. Thanks to Peter for the above tips.
#interface SlidingWindow : NSWindow
{
CGRectEdge _slidingEdge;
NSView *_wrapperView;
}
#property (nonatomic, assign) CGRectEdge slidingEdge;
#property (nonatomic, retain) NSView *wrapperView;
-(id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag;
- (NSView*)wrapperViewWithFrame:(NSRect)bounds;
- (BOOL)mayOrderOut;
#end
#interface SlidingWindow ()
- (void)adjustWrapperView;
- (void)setWindowWidth:(NSNumber*)width;
- (void)setWindowHeight:(NSNumber*)height;
#end
#implementation SlidingWindow
#synthesize slidingEdge = _slidingEdge;
#synthesize wrapperView = _wrapperView;
- (id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag
{
if ((self = [super initWithContentRect:contentRect
styleMask:NSBorderlessWindowMask
backing:backingType
defer:flag])) {
/* May want to setup some other options,
like transparent background or something */
[self setSlidingEdge:CGRectMaxYEdge];
[self setHidesOnDeactivate:YES];
[self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
}
return self;
}
- (NSView*)wrapperViewWithFrame:(NSRect)bounds
{
return [[[NSView alloc] initWithFrame:bounds] autorelease];
}
- (void)adjustWrapperView
{
if (self.wrapperView == nil) {
NSRect frame = [self frame];
NSRect bounds = NSMakeRect(0, 0, frame.size.width, frame.size.height);
NSView *wrapperView = [self wrapperViewWithFrame:bounds];
NSArray *subviews = [[[[self contentView] subviews] copy] autorelease];
for (NSView *view in subviews) {
[wrapperView addSubview:view];
}
[wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[[self contentView] addSubview:wrapperView];
self.wrapperView = wrapperView;
}
switch (self.slidingEdge) {
case CGRectMaxXEdge:
[self.wrapperView setAutoresizingMask:(NSViewHeightSizable | NSViewMaxXMargin)];
break;
case CGRectMaxYEdge:
[self.wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewMaxYMargin)];
break;
case CGRectMinXEdge:
[self.wrapperView setAutoresizingMask:(NSViewHeightSizable | NSViewMinXMargin)];
break;
case CGRectMinYEdge:
default:
[self.wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
}
}
- (void)makeKeyAndOrderFront:(id)sender
{
[self adjustWrapperView];
if ([self isVisible]) {
[super makeKeyAndOrderFront:sender];
}
else {
NSRect screenRect = [[NSScreen menubarScreen] visibleFrame];
NSRect windowRect = [self frame];
CGFloat x;
CGFloat y;
NSRect startWindowRect;
NSRect endWindowRect;
switch (self.slidingEdge) {
case CGRectMinXEdge:
x = 0;
y = (screenRect.size.height - windowRect.size.height) / 2 + screenRect.origin.y;
startWindowRect = NSMakeRect(x - windowRect.size.width, y, 0, windowRect.size.height);
break;
case CGRectMinYEdge:
x = (screenRect.size.width - windowRect.size.width) / 2 + screenRect.origin.x;
y = 0;
startWindowRect = NSMakeRect(x, y - windowRect.size.height, windowRect.size.width, 0);
break;
case CGRectMaxXEdge:
x = screenRect.size.width - windowRect.size.width + screenRect.origin.x;
y = (screenRect.size.height - windowRect.size.height) / 2 + screenRect.origin.y;
startWindowRect = NSMakeRect(x + windowRect.size.width, y, 0, windowRect.size.height);
break;
case CGRectMaxYEdge:
default:
x = (screenRect.size.width - windowRect.size.width) / 2 + screenRect.origin.x;
y = screenRect.size.height - windowRect.size.height + screenRect.origin.y;
startWindowRect = NSMakeRect(x, y + windowRect.size.height, windowRect.size.width, 0);
}
endWindowRect = NSMakeRect(x, y, windowRect.size.width, windowRect.size.height);
[self setFrame:startWindowRect display:NO animate:NO];
[super makeKeyAndOrderFront:sender];
[self setFrame:endWindowRect display:YES animate:YES];
[self performSelector:#selector(makeResizable)
withObject:nil
afterDelay:1];
}
}
- (void)makeResizable
{
NSView *wrapperView = self.wrapperView;
NSRect frame = [self frame];
NSRect bounds = NSMakeRect(0, 0, frame.size.width, frame.size.height);
[wrapperView setFrame:bounds];
[wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
}
- (void)orderOut:(id)sender
{
[self adjustWrapperView];
NSRect startWindowRect = [self frame];
NSRect endWindowRect;
switch (self.slidingEdge) {
case CGRectMinXEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
0,
startWindowRect.size.height);
break;
case CGRectMinYEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
startWindowRect.size.width,
0);
break;
case CGRectMaxXEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x + startWindowRect.size.width,
startWindowRect.origin.y,
0,
startWindowRect.size.height);
break;
case CGRectMaxYEdge:
default:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y + startWindowRect.size.height,
startWindowRect.size.width,
0);
}
[self setFrame:endWindowRect display:YES animate:YES];
switch (self.slidingEdge) {
case CGRectMaxXEdge:
case CGRectMinXEdge:
if (startWindowRect.size.width > 0) {
[self performSelector:#selector(setWindowWidth:)
withObject:[NSNumber numberWithDouble:startWindowRect.size.width]
afterDelay:0];
}
break;
case CGRectMaxYEdge:
case CGRectMinYEdge:
default:
if (startWindowRect.size.height > 0) {
[self performSelector:#selector(setWindowHeight:)
withObject:[NSNumber numberWithDouble:startWindowRect.size.height]
afterDelay:0];
}
}
[super orderOut:sender];
}
- (void)setWindowWidth:(NSNumber*)width
{
NSRect startWindowRect = [self frame];
NSRect endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
[width doubleValue],
startWindowRect.size.height);
[self setFrame:endWindowRect display:NO animate:NO];
}
- (void)setWindowHeight:(NSNumber*)height
{
NSRect startWindowRect = [self frame];
NSRect endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
startWindowRect.size.width,
[height doubleValue]);
[self setFrame:endWindowRect display:NO animate:NO];
}
- (void)resignKeyWindow
{
[self orderOut:self];
[super resignKeyWindow];
}
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (void)performClose:(id)sender
{
[self close];
}
- (void)dealloc
{
[_wrapperView release], _wrapperView = nil;
[super dealloc];
}
#end
#implementation NSScreen (MenubarScreen)
+ (NSScreen*)menubarScreen
{
NSArray *screens = [self screens];
if ([screens count] > 0) {
return [screens objectAtIndex:0];
}
return nil;
}
#end