Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

ios - Dismiss keyboard on touch anywhere outside UITextField

I am developing an iPad app that has a large number of UIViewControllers, UITableViews (with cells with accessoryViews of UITextFields) etc, etc. Many of the UIViewControllers appear within a navigation hierarchy.

There are many different places where UITextFields appear, including as UITableViewCell accessoryViews.

I would like to devise an efficient strategy for dismissing the keyboard whenever the user touches outside the UITextField currently being edited. I have searched for keyboard dismiss techniques but have not yet found an answer that explains how a general keyboard dismiss strategy might work.

For example, I like this approach, where the following code is added to any ViewController:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"* * * * * * * * *ViewControllerBase touchesBegan");

    [self.view endEditing:YES]; // dismiss the keyboard

    [super touchesBegan:touches withEvent:event];
}

...but this technique does not deal with situations where, for example, a touch occurs within a UITableView which is on display. So, I'd need to add some code to call endEditing when a UITableView is touched etc, etc. Which means that my app will be liberally sprinkled with lots of code to dismiss the keyboard when various other UIElements are touched.

I guess I could just try and identify all the different places where touches need to be intercepted and the keyboard dismissed, but it seems to me that there may be a better design pattern somewhere for handling iOS keyboard dismiss events.

Can anyone share their experiences in this matter, and recommend a specific technique for generically handling keyboard dismissal across an entire app?

Many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your view hierarchy lives inside a UIWindow. The UIWindow is responsible for forwarding touch events to the correct view in its sendEvent: method. Let's make a subclass of UIWindow to override sendEvent:.

@interface MyWindow : UIWindow
@end

The window will need a reference to the current first responder, if there is one. You might decide to also use UITextView, so we'll observe notifications from both text fields and text views.

@implementation MyWindow {
    UIView *currentFirstResponder_;
}

- (void)startObservingFirstResponder {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(observeBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [center addObserver:self selector:@selector(observeEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
    [center addObserver:self selector:@selector(observeBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
    [center addObserver:self selector:@selector(observeEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil];
}

- (void)stopObservingFirstResponder {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
    [center removeObserver:self name:UITextFieldTextDidEndEditingNotification object:nil];
    [center removeObserver:self name:UITextViewTextDidBeginEditingNotification object:nil];
    [center removeObserver:self name:UITextViewTextDidEndEditingNotification object:nil];
}

- (void)observeBeginEditing:(NSNotification *)note {
    currentFirstResponder_ = note.object;
}

- (void)observeEndEditing:(NSNotification *)note {
    if (currentFirstResponder_ == note.object) {
        currentFirstResponder_ = nil;
    }
}

The window will start observing the notifications when it's initialized, and stop when it's deallocated:

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self commonInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    [self startObservingFirstResponder];
}

- (void)dealloc {
    [self stopObservingFirstResponder];
}

We'll override sendEvent: to “adjust” the first responder based on the event, and then call super's sendEvent: to send the event normally.

- (void)sendEvent:(UIEvent *)event {
    [self adjustFirstResponderForEvent:event];
    [super sendEvent:event];
}

We don't need to do anything about the first responder if there is no first responder. If there is a first responder, and it contains a touch, we don't want to force it to resign. (Remember, there can be multiple touches simultaneously!) If there is a first responder, and a new touch appears in another view that can become the first responder, the system will handle that correctly automatically, so we also want to ignore that case. But if there is a first responder, and it doesn't contain any touches, and a new touch appears in a view that can't become first responder, we want to make the first responder resign.

- (void)adjustFirstResponderForEvent:(UIEvent *)event {
    if (currentFirstResponder_
        && ![self eventContainsTouchInFirstResponder:event]
        && [self eventContainsNewTouchInNonresponder:event]) {
        [currentFirstResponder_ resignFirstResponder];
    }
}

Reporting whether an event contains a touch in the first responder is easy:

- (BOOL)eventContainsTouchInFirstResponder:(UIEvent *)event {
    for (UITouch *touch in [event touchesForWindow:self]) {
        if (touch.view == currentFirstResponder_)
            return YES;
    }
    return NO;
}

Reporting whether an event contains a new touch in a view that can't become first responder is almost as easy:

- (BOOL)eventContainsNewTouchInNonresponder:(UIEvent *)event {
    for (UITouch *touch in [event touchesForWindow:self]) {
        if (touch.phase == UITouchPhaseBegan && ![touch.view canBecomeFirstResponder])
            return YES;
    }
    return NO;
}

@end

Once you've implemented this class, you need to change your app to use it instead of UIWindow.

If you're creating your UIWindow in application:didFinishLaunchingWithOptions:, you need to #import "MyWindow.h" at the top of your AppDelegate.m, and then change application:didFinishLaunchingWithOptions: to create a MyWindow instead of a UIWindow.

If you're creating your UIWindow in a nib, you need to set the custom class of the window to MyWindow in the nib.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...