Overriding keyDown causes issues to a NSTableView - objective-c

In my NSTableView subclass MyTableView I've overwritten
- (void) keyDown:(NSEvent *)event {
if ( [event keyCode] == 51 || [event keyCode] == 117 ) {
[super keyDown:event];
return;
}
}
51 is the code for the delete button. I'm expecting the table view to delete the selected item as before the subclassing.
The event is correctly caught and the keyDown method of the superclass is invoked. However, the item is not deleted anymore. Why ?
Thanks

Recommend you override keyDown: in your window class.
-(void) keyDown: (NSEvent *) event
{
NSString *chars = [event characters];
unichar character = [chars characterAtIndex: 0];
if (character == NSDeleteCharacter || character == NSBackspaceCharacter)
{
NSTableView* view = (NSTableView*)[self firstResponder];
if(view == theTableView)
{
// do something to delete the item from your data model and reload the tableview
}
}
}

If you are trying just to invoke a specific method when the Delete key is pressed, I'd suggest overriding the -deleteBackward: method (part of NSResponder), because it isolates this interception more specifically. It also manages the problem of remapped keyboards, macros, etc.
There's also -deleteForward for the delete key instead of the backspace key.
-(void)deleteBackward:(id)sender
{
// do my override here
// do this only if super implements deleteBackward:
[super deleteBackward: sender]
}

Related

dragging text produces 2 insertion points in NSTextView, and can not remove it

This is the error picture:
My class is a subclass of NSTextView, it supports dragging. but When I drag text to former location, there will be a sticked inserting point.
Then I click elsewhere ,the normal insertion point appears at the end of text(which is correct),
but the first point did not disappear automatically, even though I delete the whole string.
there are only 3 method or property in NSTextView related to insertion point.
#property (readonly) BOOL shouldDrawInsertionPoint;
#property (copy) NSColor *insertionPointColor;
- (void)updateInsertionPointStateAndRestartTimer:(BOOL)restartFlag;
- (void)drawInsertionPointInRect:(NSRect)rect color:(NSColor *)color turnedOn:(BOOL)flag;
The first one is readonly, I tried the second one ,I set white color, when dragging and original color after dragActionEnded. I did not work.
Waiting for your resolution.
Thanks!
The following is the drag delegate code I wrote.
#pragma mark - Destination Operations
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
/------------------------------------------------------
method called whenever a drag enters our drop zone
--------------------------------------------------------/
// Check if the pasteboard contains image data and source/user wants it copied
if ([sender draggingSourceOperationMask] & NSDragOperationCopy )
{
//accept data as a copy operation
return NSDragOperationCopy;
}
return NSDragOperationNone;
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
//check to see if we can accept the data
NSURL *fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
if (fileURL == nil) {
return NO;}
NSString *filePathAndName = [[NSString alloc] initWithUTF8String:[fileURL fileSystemRepresentation]];
if (filePathAndName == nil)
{
return NO;
}
NSString *fileExtension = [[filePathAndName pathExtension] uppercaseString];
if (fileExtension == nil)
{
return NO;
}
if ([fileExtension isEqualToString:#"JPG"] ||
[fileExtension isEqualToString:#"JPEG"] ||
[fileExtension isEqualToString:#"PNG"] ||
[fileExtension isEqualToString:#"GIF"] ||
[fileExtension isEqualToString:#"BMP"])
{
return YES;
}
else
{
return NO;
}
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender{
if ( [sender draggingSource] != self )
{
if ( [[[sender draggingPasteboard] types] containsObject:NSFilenamesPboardType] ) {
NSURL* fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
NSArray *files = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
[[NSNotificationCenter defaultCenter] postNotificationName:ZayhuSendPicToPeer object:self userInfo:#{#"filesArray":files}];
}
}
return YES;
}
- (NSString *)preferredPasteboardTypeFromArray:(NSArray *)availableTypes restrictedToTypesFromArray:(NSArray *)allowedTypes{
if ([availableTypes containsObject:NSPasteboardTypeString])
{
return NSPasteboardTypeString;
}
return [super preferredPasteboardTypeFromArray:availableTypes restrictedToTypesFromArray:allowedTypes];
}
I have encountered your problem.
My way to solve this problem is not subclassing NSTextView to do all drag and drop tasks but put NSTextView on a custom view and let the custom view do the main part of the job.
If i subclassed NSTextView to be the drag destination, i encountered some other UI problems such as disappearing insertion point when the textview is backed by a CALayer.
The following code are written in Swift, but it stills convey the idea for the solution.
First of all, for text drag & drop. You can subclass NSTextView and just override acceptableDragTypes
override var acceptableDragTypes : [String] {
return [NSStringPboardType]
}
For other types of drag & drop, let the custom view deal with them. Take dragging files as example,
class MyCustomView: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
registerForDraggedTypes([NSFilenamesPboardType])
}
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if sender.draggingSource() === self {
return .None
}
return sender.draggingSourceOperationMask()
}
override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool {
//add your custom logic here
return true
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
//add your custom logic here
return true
}
}
I had need of subclassing a NSTextView for some other reasons and needed to add some custom object dragging. I ran into the same things you did with the insertion point weirdness.
In my case, instead of adding another view to handle the custom object logic I did override the performDragOperation and just called the super in the case that it wasn't my specific type. This seemed to work perfectly.
This allowed the default handling the String case in its natural way and the insertion UI stuff all cleared up.

Disable long press menu in text area/input UIWebview

This seems to be one of the most frequently discussed topics here but I couldn't find a solution which actually works. I'm posting this question to share a solution which I found as well as hoping to find a better/cleaner solution
Description of situation:
There is a UIWebview in my application
There is text input/area in the webview
Long pressing on the text area/input brings up a context menu with 'cut', 'copy', 'define' etc.
We need to disable this menu without disabling user input.
What I've tried so far
(Stuff that doesn't work) :
Override canPerformAction
This solution tells us to add canPerformAction:withSender: to either subclass of UIWebview or in a delegate of UIWebview.
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(defineSelection:))
{
return NO;
}
else if (action == #selector(translateSelection:))
{
return NO;
}
else if (action == #selector(copy:))
{
return NO;
}
return [super canPerformAction:action withSender:sender];
}
Does not work because the canPerformAction: in this class is does not get called for menu items displayed.
Since the sharedMenuController interacts with the first responder in the Responder chain, implementing canPerformAction in the container skipped select and selectAll because they had already been handled by a child menu.
Manipulating CSS
Add the following to CSS:
html {
-webkit-user-select: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
This does work on images and hyperlinks but not on inputs.
:(
The root cause of the first solution not working is the subview called UIWebBrowserView. This seems to be the view whose canPerformAction returns true for any action displayed in the context menu.
Since this UIWebBrowserView is a private class we shouldn't try to subclass it (because it will get your app rejected).
So what we do instead is we make another method called mightPerformAction:withSender:, like so-
- (BOOL)mightPerformAction:(SEL)action withSender:(id)sender {
NSLog(#"******Action!! %#******",NSStringFromSelector(action));
if (action == #selector(copy:))
{
NSLog(#"Copy Selector");
return NO;
}
else if (action == #selector(cut:))
{
NSLog(#"cut Selector");
return NO;
}
else if (action == NSSelectorFromString(#"_define:"))
{
NSLog(#"define Selector");
return NO;
}
else if (action == #selector(paste:))
{
NSLog(#"paste Selector");
return NO;
}
else
{
return [super canPerformAction:action withSender:sender];
}
}
and add another method to replace canPerformAction:withSender: with mightPerformAction:withSender:
- (void) replaceUIWebBrowserView: (UIView *)view
{
//Iterate through subviews recursively looking for UIWebBrowserView
for (UIView *sub in view.subviews) {
[self replaceUIWebBrowserView:sub];
if ([NSStringFromClass([sub class]) isEqualToString:#"UIWebBrowserView"]) {
Class class = sub.class;
SEL originalSelector = #selector(canPerformAction:withSender:);
SEL swizzledSelector = #selector(mightPerformAction:withSender:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self.class, swizzledSelector);
//add the method mightPerformAction:withSender: to UIWebBrowserView
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
//replace canPerformAction:withSender: with mightPerformAction:withSender:
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
And finally call it in the viewDidLoad of the ViewController:
[self replaceUIWebBrowserView:self.webView];
Note: Add #import <objc/runtime.h> to your viewController then error(Method) will not shown.
Note: I am using NSSelectorFromString method to avoid detection of private API selectors during the review process.
Also you can hide menu:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(menuWillBeShown:) name:UIMenuControllerWillShowMenuNotification object:nil];
...
- (void)menuWillBeShown:(NSNotification *)notification {
dispatch_async(dispatch_get_main_queue(),^{
[[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
});
}
The essential trick here is dispatch_async.

Force NSTextField to send textDidEndEditing

I have a subclass of NSTextField that I made so that when a user is done editing the field, the text field will lose focus. I also have it set up so whenever the user clicks on the main view, this will act as losing focus on the textfield. And this all works great. Now I want to add some additional capabilities to the subclass.
I want the textfield to send a textDidEndEditing every time a user clicks anywhere outside of the box. This includes when a user clicks on another UI component. The behavior I'm seeing right now is that when a user clicks on another UI component (let's say a combo box) the action does not trigger. Is there a way to force this? Besides manually adding it as a part of the other components actions?
Any help would be appreciated!
Here's the code for my textDidEndEditing function
- (void)textDidEndEditing:(NSNotification *)notification
{
NSString *file = nil;
char c = ' ';
int index = 0;
[super textDidEndEditing:notification];
if ([self isEditable])
{
// is there a valid string to display?
file = [self stringValue];
if ([file length] > 0)
{
c = [file characterAtIndex:([file length] - 1)];
if (c == '\n') // check for white space at the end
{
// whitespace at the end... remove
NSMutableString *newfile = [[NSMutableString alloc] init];
c = [file characterAtIndex:index++];
do
{
[newfile appendFormat:#"%c", c];
c = [file characterAtIndex:index++];
}
while ((c != '\n') && (index < [file length]));
[self setStringValue:newfile];
file = newfile;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:#"inputFileEntered" object:self];
}
}
// since we're leaving this box, show no text in this box as selected.
// and deselect this box as the first responder
[self setSelectedText:0];
[[NSNotificationCenter defaultCenter]
postNotificationName:#"setResponderToNil" object:self];
}
Where "setSelectedText" is a public function in the text field subclass:
- (void)setSelectedText:(int) length
{
int start = 0;
NSText *editor = [self.window fieldEditor:YES forObject:self];
NSRange range = {start, length};
[editor setSelectedRange:range];
}
And the "setResponderToNil" notification is a part of my NSView subclass:
- (void)setResponderToNil
{
AppDelegate *delegate = (AppDelegate *)[NSApp delegate];
[delegate.window makeFirstResponder:nil];
}
I think I found a way to do this. It may not be the most eloquent, but it seems to work with the type of behavior I want.
I added an mouse event listener to the app's main controller:
event_monitor_mousedown_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSRightMouseDown
handler:^NSEvent *(NSEvent * event)
{
NSResponder *resp = [[[NSApplication sharedApplication] keyWindow] firstResponder];
if ([resp isKindOfClass:[NSTextView class]])
{
// set UI in proper state - remove focus from text field
// even when touching a new window for the first time
[[NSNotificationCenter defaultCenter]
postNotificationName:#"setResponderToNil" object:self];
[self setStopState];
}
return event;
}];
This event checks the current responder in the application on any mouseDown action. If it's a textView object (which is type of the object that would be the first responder when editing an NSTextField) it will send the notification to set the firstResponder to nil. This forces the textDidEndEditing notification. I want to play around with it some more to see if I'm getting the right expected behavior. I hope this helps someone out there!

Override keydownevent in NSTextfield

I made a subclass of the nstextfield and i override the keydown event but my code doesn't work, then i override de keyup event and the code works perfectly.
My keydown code(doesn't work):
-(void)keyDown:(NSEvent *)event {
NSLog(#"Key released: %hi", [event keyCode]);
if ([event keyCode]==125){
[[self window] selectKeyViewFollowingView:self];
}
if ([event keyCode]==126){
[[self window] selectKeyViewPrecedingView:self];
}
}
My keyup code (it works):
-(void)keyUp:(NSEvent*)event
{if ([event keyCode]==125){
[[self window] selectKeyViewFollowingView:self];
}
if ([event keyCode]==126){
[[self window] selectKeyViewPrecedingView:self];
}
if ([event keyCode]==36){
[[self window] selectKeyViewFollowingView:self];
}
}
I don't see where is the problem with my keydown code. Any suggest will be accepted
EDIT:
I have read that you have to subclass NSTextView instead of NSTextField.
You can do it without subclassing by using NSTextFieldDelegate methods:
As #Darren Inksetter said, you can use control:textView:doCommandBySelector:
First, declare NSTextFieldDelegate in your interface tag.
Then implement the method:
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
if( commandSelector == #selector(moveUp:) ){
// Do yourthing here, like selectKeyViewFollowingView
return YES; // Return YES means don't pass it along responders chain. Return NO if you still want system's action on this key.
}
if( commandSelector == #selector(moveDown:) ){
// Do the same with the keys you want to track
return YES;
}
return NO;
}
The keydown event can't be overriden in a NSTextField, if you want , you could override the keydown event of the super view or you could use a NSTextView or just override the keyup event in the NSTextField
You will want to look at
control:textView:doCommandBySelector:
http://developer.apple.com/library/mac/#documentation/cocoa/reference/NSControlTextEditingDelegate_Protocol/Reference/Reference.html
Swift 5 example.
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
switch commandSelector {
case #selector(moveUp(_:)):
impl.tableView.doCommand(by: commandSelector)
return true
case #selector(moveDown(_:)):
impl.tableView.doCommand(by: commandSelector)
return true
default: return false
}
}

Get the current first responder without using a private API

I submitted my app a little over a week ago and got the dreaded rejection email today. It tells me that my app cannot be accepted because I'm using a non-public API; specifically, it says,
The non-public API that is included in your application is firstResponder.
Now, the offending API call is actually a solution I found here on SO:
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView *firstResponder = [keyWindow performSelector:#selector(firstResponder)];
How do I get the current first responder on the screen? I'm looking for a way that won't get my app rejected.
If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES]
In one of my applications I often want the first responder to resign if the user taps on the background. For this purpose I wrote a category on UIView, which I call on the UIWindow.
The following is based on that and should return the first responder.
#implementation UIView (FindFirstResponder)
- (id)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.subviews) {
id responder = [subView findFirstResponder];
if (responder) return responder;
}
return nil;
}
#end
iOS 7+
- (id)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.view.subviews) {
if ([subView isFirstResponder]) {
return subView;
}
}
return nil;
}
Swift:
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
for subview in subviews {
if let firstResponder = subview.firstResponder {
return firstResponder
}
}
return nil
}
}
Usage example in Swift:
if let firstResponder = view.window?.firstResponder {
// do something with `firstResponder`
}
A common way of manipulating the first responder is to use nil targeted actions. This is a way of sending an arbitrary message to the responder chain (starting with the first responder), and continuing down the chain until someone responds to the message (has implemented a method matching the selector).
For the case of dismissing the keyboard, this is the most effective way that will work no matter which window or view is first responder:
[[UIApplication sharedApplication] sendAction:#selector(resignFirstResponder) to:nil from:nil forEvent:nil];
This should be more effective than even [self.view.window endEditing:YES].
(Thanks to BigZaphod for reminding me of the concept)
Here's a category that allows you to quickly find the first responder by calling [UIResponder currentFirstResponder]. Just add the following two files to your project:
UIResponder+FirstResponder.h:
#import <Cocoa/Cocoa.h>
#interface UIResponder (FirstResponder)
+(id)currentFirstResponder;
#end
UIResponder+FirstResponder.m:
#import "UIResponder+FirstResponder.h"
static __weak id currentFirstResponder;
#implementation UIResponder (FirstResponder)
+(id)currentFirstResponder {
currentFirstResponder = nil;
[[UIApplication sharedApplication] sendAction:#selector(findFirstResponder:) to:nil from:nil forEvent:nil];
return currentFirstResponder;
}
-(void)findFirstResponder:(id)sender {
currentFirstResponder = self;
}
#end
The trick here is that sending an action to nil sends it to the first responder.
(I originally published this answer here: https://stackoverflow.com/a/14135456/322427)
Here is a Extension implemented in Swift based on Jakob Egger's most excellent answer:
import UIKit
extension UIResponder {
// Swift 1.2 finally supports static vars!. If you use 1.1 see:
// http://stackoverflow.com/a/24924535/385979
private weak static var _currentFirstResponder: UIResponder? = nil
public class func currentFirstResponder() -> UIResponder? {
UIResponder._currentFirstResponder = nil
UIApplication.sharedApplication().sendAction("findFirstResponder:", to: nil, from: nil, forEvent: nil)
return UIResponder._currentFirstResponder
}
internal func findFirstResponder(sender: AnyObject) {
UIResponder._currentFirstResponder = self
}
}
Swift 4
import UIKit
extension UIResponder {
private weak static var _currentFirstResponder: UIResponder? = nil
public static var current: UIResponder? {
UIResponder._currentFirstResponder = nil
UIApplication.shared.sendAction(#selector(findFirstResponder(sender:)), to: nil, from: nil, for: nil)
return UIResponder._currentFirstResponder
}
#objc internal func findFirstResponder(sender: AnyObject) {
UIResponder._currentFirstResponder = self
}
}
It's not pretty, but the way I resign the firstResponder when I don't know what that the responder is:
Create an UITextField, either in IB or programmatically. Make it Hidden. Link it up to your code if you made it in IB.
Then, when you want to dismiss the keyboard, you switch the responder to the invisible text field, and immediately resign it:
[self.invisibleField becomeFirstResponder];
[self.invisibleField resignFirstResponder];
For a Swift 3 & 4 version of nevyn's answer:
UIApplication.shared.sendAction(#selector(UIView.resignFirstResponder), to: nil, from: nil, for: nil)
Here's a solution which reports the correct first responder (many other solutions won't report a UIViewController as the first responder, for example), doesn't require looping over the view hierarchy, and doesn't use private APIs.
It leverages Apple's method sendAction:to:from:forEvent:, which already knows how to access the first responder.
We just need to tweak it in 2 ways:
Extend UIResponder so it can execute our own code on the first responder.
Subclass UIEvent in order to return the first responder.
Here is the code:
#interface ABCFirstResponderEvent : UIEvent
#property (nonatomic, strong) UIResponder *firstResponder;
#end
#implementation ABCFirstResponderEvent
#end
#implementation UIResponder (ABCFirstResponder)
- (void)abc_findFirstResponder:(id)sender event:(ABCFirstResponderEvent *)event {
event.firstResponder = self;
}
#end
#implementation ViewController
+ (UIResponder *)firstResponder {
ABCFirstResponderEvent *event = [ABCFirstResponderEvent new];
[[UIApplication sharedApplication] sendAction:#selector(abc_findFirstResponder:event:) to:nil from:nil forEvent:event];
return event.firstResponder;
}
#end
Using Swift and with a specific UIView object this might help:
func findFirstResponder(inView view: UIView) -> UIView? {
for subView in view.subviews as! [UIView] {
if subView.isFirstResponder() {
return subView
}
if let recursiveSubView = self.findFirstResponder(inView: subView) {
return recursiveSubView
}
}
return nil
}
Just place it in your UIViewController and use it like this:
let firstResponder = self.findFirstResponder(inView: self.view)
Take note that the result is an Optional value so it will be nil in case no firstResponder was found in the given views subview hierarchy.
The first responder can be any instance of the class UIResponder, so there are other classes that might be the first responder despite the UIViews. For example UIViewController might also be the first responder.
In this gist you will find a recursive way to get the first responder by looping through the hierarchy of controllers starting from the rootViewController of the application's windows.
You can retrieve then the first responder by doing
- (void)foo
{
// Get the first responder
id firstResponder = [UIResponder firstResponder];
// Do whatever you want
[firstResponder resignFirstResponder];
}
However, if the first responder is not a subclass of UIView or UIViewController, this approach will fail.
To fix this problem we can do a different approach by creating a category on UIResponder and perform some magic swizzeling to be able to build an array of all living instances of this class. Then, to get the first responder we can simple iterate and ask each object if -isFirstResponder.
This approach can be found implemented in this other gist.
Hope it helps.
Iterate over the views that could be the first responder and use - (BOOL)isFirstResponder to determine if they currently are.
Rather than iterate through the collection of views looking for the one that has isFirstResponder set, I too send a message to nil, but I store the receiver of the message so I can return it and do whatever I wish with it.
Additionally, I zero out the optional that holds the found responder in a defer statement from within the call itself. This ensures no references remain--even weak ones--at the end of the call.
import UIKit
private var _foundFirstResponder: UIResponder? = nil
extension UIResponder {
static var first:UIResponder? {
// Sending an action to 'nil' implicitly sends it to the first responder
// where we simply capture it and place it in the _foundFirstResponder variable.
// As such, the variable will contain the current first responder (if any) immediately after this line executes
UIApplication.shared.sendAction(#selector(UIResponder.storeFirstResponder(_:)), to: nil, from: nil, for: nil)
// The following 'defer' statement runs *after* this getter returns,
// thus releasing any strong reference held by the variable immediately thereafter
defer {
_foundFirstResponder = nil
}
// Return the found first-responder (if any) back to the caller
return _foundFirstResponder
}
// Make sure to mark this with '#objc' since it has to be reachable as a selector for `sendAction`
#objc func storeFirstResponder(_ sender: AnyObject) {
// Capture the recipient of this message (self), which is the first responder
_foundFirstResponder = self
}
}
With the above, I can resign the first responder by simply doing this...
UIResponder.first?.resignFirstResponder()
But since my API actually hands back whatever the first responder is, I can do whatever I want with it.
Here's an example that checks if the current first responder is a UITextField with a helpMessage property set, and if so, shows it in a help bubble right next to the control. We call this from a 'Quick Help' button on our screen.
func showQuickHelp(){
if let textField = UIResponder?.first as? UITextField,
let helpMessage = textField.helpMessage {
textField.showHelpBubble(with:helpMessage)
}
}
The support for the above is defined in an extension on UITextField like so...
extension UITextField {
var helpMessage:String? { ... }
func showHelpBubble(with message:String) { ... }
}
Now to support this feature, all we have to do is decide which text fields have help messages and the UI takes care of the rest for us.
Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification, which you can observe if you want to watch the firstResponder change.
If you just need to kill the keyboard when the user taps on a background area why not add a gesture recognizer and use it to send the [[self view] endEditing:YES] message?
you can add the Tap gesture recogniser in the xib or storyboard file and connect it to an action,
looks something like this then finished
- (IBAction)displayGestureForTapRecognizer:(UITapGestureRecognizer *)recognizer{
[[self view] endEditing:YES];
}
Just it case here is Swift version of awesome Jakob Egger's approach:
import UIKit
private weak var currentFirstResponder: UIResponder?
extension UIResponder {
static func firstResponder() -> UIResponder? {
currentFirstResponder = nil
UIApplication.sharedApplication().sendAction(#selector(self.findFirstResponder(_:)), to: nil, from: nil, forEvent: nil)
return currentFirstResponder
}
func findFirstResponder(sender: AnyObject) {
currentFirstResponder = self
}
}
This is what I did to find what UITextField is the firstResponder when the user clicks Save/Cancel in a ModalViewController:
NSArray *subviews = [self.tableView subviews];
for (id cell in subviews )
{
if ([cell isKindOfClass:[UITableViewCell class]])
{
UITableViewCell *aCell = cell;
NSArray *cellContentViews = [[aCell contentView] subviews];
for (id textField in cellContentViews)
{
if ([textField isKindOfClass:[UITextField class]])
{
UITextField *theTextField = textField;
if ([theTextField isFirstResponder]) {
[theTextField resignFirstResponder];
}
}
}
}
}
This is what I have in my UIViewController Category. Useful for many things, including getting first responder. Blocks are great!
- (UIView*) enumerateAllSubviewsOf: (UIView*) aView UsingBlock: (BOOL (^)( UIView* aView )) aBlock {
for ( UIView* aSubView in aView.subviews ) {
if( aBlock( aSubView )) {
return aSubView;
} else if( ! [ aSubView isKindOfClass: [ UIControl class ]] ){
UIView* result = [ self enumerateAllSubviewsOf: aSubView UsingBlock: aBlock ];
if( result != nil ) {
return result;
}
}
}
return nil;
}
- (UIView*) enumerateAllSubviewsUsingBlock: (BOOL (^)( UIView* aView )) aBlock {
return [ self enumerateAllSubviewsOf: self.view UsingBlock: aBlock ];
}
- (UIView*) findFirstResponder {
return [ self enumerateAllSubviewsUsingBlock:^BOOL(UIView *aView) {
if( [ aView isFirstResponder ] ) {
return YES;
}
return NO;
}];
}
With a category on UIResponder, it is possible to legally ask the UIApplication object to tell you who the first responder is.
See this:
Is there any way of asking an iOS view which of its children has first responder status?
You can choose the following UIView extension to get it (credit by Daniel):
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
return subviews.first(where: {$0.firstResponder != nil })
}
}
You can try also like this:
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
for (id textField in self.view.subviews) {
if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder]) {
[textField resignFirstResponder];
}
}
}
I didn't try it but it seems a good solution
This is good candidate for recursion! No need to add a category to UIView.
Usage (from your view controller):
UIView *firstResponder = [self findFirstResponder:[self view]];
Code:
// This is a recursive function
- (UIView *)findFirstResponder:(UIView *)view {
if ([view isFirstResponder]) return view; // Base case
for (UIView *subView in [view subviews]) {
if ([self findFirstResponder:subView]) return subView; // Recursion
}
return nil;
}
you can call privite api like this ,apple ignore:
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
SEL sel = NSSelectorFromString(#"firstResponder");
UIView *firstResponder = [keyWindow performSelector:sel];
Swift version of #thomas-müller's response
extension UIView {
func firstResponder() -> UIView? {
if self.isFirstResponder() {
return self
}
for subview in self.subviews {
if let firstResponder = subview.firstResponder() {
return firstResponder
}
}
return nil
}
}
I would like to shared with you my implementation for find first responder in anywhere of UIView. I hope it helps and sorry for my english. Thanks
+ (UIView *) findFirstResponder:(UIView *) _view {
UIView *retorno;
for (id subView in _view.subviews) {
if ([subView isFirstResponder])
return subView;
if ([subView isKindOfClass:[UIView class]]) {
UIView *v = subView;
if ([v.subviews count] > 0) {
retorno = [self findFirstResponder:v];
if ([retorno isFirstResponder]) {
return retorno;
}
}
}
}
return retorno;
}
The solution from romeo https://stackoverflow.com/a/2799675/661022 is cool, but I noticed that the code needs one more loop. I was working with tableViewController.
I edited the script and then I checked. Everything worked perfect.
I recommed to try this:
- (void)findFirstResponder
{
NSArray *subviews = [self.tableView subviews];
for (id subv in subviews )
{
for (id cell in [subv subviews] ) {
if ([cell isKindOfClass:[UITableViewCell class]])
{
UITableViewCell *aCell = cell;
NSArray *cellContentViews = [[aCell contentView] subviews];
for (id textField in cellContentViews)
{
if ([textField isKindOfClass:[UITextField class]])
{
UITextField *theTextField = textField;
if ([theTextField isFirstResponder]) {
NSLog(#"current textField: %#", theTextField);
NSLog(#"current textFields's superview: %#", [theTextField superview]);
}
}
}
}
}
}
}
Update: I was wrong. You can indeed use UIApplication.shared.sendAction(_:to:from:for:) to call the first responder demonstrated in this link: http://stackoverflow.com/a/14135456/746890.
Most of the answers here can't really find the current first responder if it is not in the view hierarchy. For example, AppDelegate or UIViewController subclasses.
There is a way to guarantee you to find it even if the first responder object is not a UIView.
First lets implement a reversed version of it, using the next property of UIResponder:
extension UIResponder {
var nextFirstResponder: UIResponder? {
return isFirstResponder ? self : next?.nextFirstResponder
}
}
With this computed property, we can find the current first responder from bottom to top even if it's not UIView. For example, from a view to the UIViewController who's managing it, if the view controller is the first responder.
However, we still need a top-down resolution, a single var to get the current first responder.
First with the view hierarchy:
extension UIView {
var previousFirstResponder: UIResponder? {
return nextFirstResponder ?? subviews.compactMap { $0.previousFirstResponder }.first
}
}
This will search for the first responder backwards, and if it couldn't find it, it would tell its subviews to do the same thing (because its subview's next is not necessarily itself). With this we can find it from any view, including UIWindow.
And finally, we can build this:
extension UIResponder {
static var first: UIResponder? {
return UIApplication.shared.windows.compactMap({ $0.previousFirstResponder }).first
}
}
So when you want to retrieve the first responder, you can call:
let firstResponder = UIResponder.first
Code below work.
- (id)ht_findFirstResponder
{
//ignore hit test fail view
if (self.userInteractionEnabled == NO || self.alpha <= 0.01 || self.hidden == YES) {
return nil;
}
if ([self isKindOfClass:[UIControl class]] && [(UIControl *)self isEnabled] == NO) {
return nil;
}
//ignore bound out screen
if (CGRectIntersectsRect(self.frame, [UIApplication sharedApplication].keyWindow.bounds) == NO) {
return nil;
}
if ([self isFirstResponder]) {
return self;
}
for (UIView *subView in self.subviews) {
id result = [subView ht_findFirstResponder];
if (result) {
return result;
}
}
return nil;
}
Simplest way to find first responder:
func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool
The default implementation dispatches the action method to the given
target object or, if no target is specified, to the first responder.
Next step:
extension UIResponder
{
private weak static var first: UIResponder? = nil
#objc
private func firstResponderWhereYouAre(sender: AnyObject)
{
UIResponder.first = self
}
static var actualFirst: UIResponder?
{
UIApplication.shared.sendAction(#selector(findFirstResponder(sender:)), to: nil, from: nil, for: nil)
return UIResponder.first
}
}
Usage:
Just get UIResponder.actualFirst for your own purposes.