Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
//
// 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
You can’t perform that action at this time.