Skip to content

Instantly share code, notes, and snippets.

@petermaurer
Last active July 29, 2016 08:35
Show Gist options
  • Save petermaurer/dd401ce79cb5bf2db73726251567b702 to your computer and use it in GitHub Desktop.
Save petermaurer/dd401ce79cb5bf2db73726251567b702 to your computer and use it in GitHub Desktop.
Find first text field/view, make first responder
- (BOOL)makeFirstTextInputSubviewKeyView {
NSWindow *theWindow = [self window];
if ([theWindow isVisible]) {
NSArray *theTopLevelSubviews = [self subviews];
if ([theTopLevelSubviews count]>0) {
Class theTextFieldClass = [NSTextField class];
Class theTextViewClass = [NSTextView class];
NSMutableArray *theTextInputSubviews = [NSMutableArray array];
__block void (^PMCollectTextInputSubviews)(NSArray *) = ^(NSArray *theSubviews) {
for (NSView *aSubview in theSubviews) {
if (![aSubview isHidden]) {
if (([aSubview isKindOfClass: theTextFieldClass] || [aSubview isKindOfClass: theTextViewClass]) && [aSubview canBecomeKeyView]) {
[theTextInputSubviews addObject: aSubview];
}
PMCollectTextInputSubviews([aSubview subviews]);
}
}
};
PMCollectTextInputSubviews(theTopLevelSubviews);
NSUInteger theNumberOfTextInputSubviews = [theTextInputSubviews count];
if (theNumberOfTextInputSubviews>0) {
if (theNumberOfTextInputSubviews>1) {
BOOL isRightToLeftLayout = ([self userInterfaceLayoutDirection]==NSUserInterfaceLayoutDirectionRightToLeft);
[theTextInputSubviews sortUsingComparator: ^(NSView *theFirstView, NSView *theSecondView) {
NSPoint theFirstOrigin = [theFirstView convertRect: [theFirstView bounds] toView: nil].origin;
NSPoint theSecondOrigin = [theSecondView convertRect: [theSecondView bounds] toView: nil].origin;
CGFloat aDelta = theFirstOrigin.y - theSecondOrigin.y;
if (aDelta>0.1) {
return NSOrderedAscending;
}
if (aDelta<-0.1) {
return NSOrderedDescending;
}
aDelta = (isRightToLeftLayout ? theFirstOrigin.x - theSecondOrigin.x : theSecondOrigin.x - theFirstOrigin.x);
if (aDelta>0.1) {
return NSOrderedAscending;
}
if (aDelta<-0.1) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];
}
return [theWindow makeFirstResponder: [theTextInputSubviews objectAtIndex: 0]];
}
}
}
return NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment