Last active
May 31, 2020 23:55
-
-
Save steventroughtonsmith/7445550 to your computer and use it in GitHub Desktop.
Example of dynamic iOS UI that changes based on the connection/disconnection of a hardware keyboard, based on suggestions from @JohnRHeaton. Requires linking to private GraphicsServices framework. rdar://problem/15447952
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// HWKViewController.m | |
// HardwareKeyboardUI | |
// | |
// Created by Steven Troughton-Smith on 13/11/2013. | |
// Copyright (c) 2013 High Caffeine Content. All rights reserved. | |
// | |
#import "HWKViewController.h" | |
extern const char* kGSEventHardwareKeyboardAvailabilityChangedNotification; // = "GSEventHardwareKeyboardAttached" | |
extern BOOL GSEventIsHardwareKeyboardAttached(); | |
static void HardwareKeyboardStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) | |
{ | |
NSLog(@"Darwin notification NAME = %@",name); | |
[[NSNotificationCenter defaultCenter] postNotificationName:@"HardwareKeyboardStatusChanged" object:(__bridge id)object userInfo:(__bridge id)userInfo]; | |
} | |
@implementation HWKViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), | |
NULL, // observer | |
HardwareKeyboardStatusChanged, // callback | |
(__bridge CFStringRef)[NSString stringWithUTF8String:kGSEventHardwareKeyboardAvailabilityChangedNotification], // event name | |
NULL, // object | |
CFNotificationSuspensionBehaviorDeliverImmediately); | |
[[NSNotificationCenter defaultCenter] addObserverForName:@"HardwareKeyboardStatusChanged" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { | |
if (GSEventIsHardwareKeyboardAttached()) | |
{ | |
[self.helloButton setTitle:@"⌘H Hello" forState:UIControlStateNormal]; | |
} | |
else | |
{ | |
[self.helloButton setTitle:@"Hello" forState:UIControlStateNormal]; | |
} | |
}]; | |
[[NSNotificationCenter defaultCenter] postNotificationName:@"HardwareKeyboardStatusChanged" object:nil]; // set initial state | |
} | |
#pragma mark - | |
-(BOOL)canBecomeFirstResponder | |
{ | |
return YES; | |
} | |
-(NSArray *)keyCommands | |
{ | |
return @[[UIKeyCommand keyCommandWithInput:@"h" modifierFlags:UIKeyModifierCommand action:@selector(helloPressed:)]]; | |
} | |
#pragma mark - | |
- (IBAction)helloPressed:(id)sender | |
{ | |
self.alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"Hello World!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; | |
[self.alertView show]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment