views:

1234

answers:

3

So I have a UITextView that I'm using to allow the user to submit some text.

My problem is, I can't seem to figure out how to allow the user to 'Cancel' by tapping away from the UITextView.

A: 
[myTextField resignFirstResponder];

(And this isn't the first time I've answered that here, ie please try searching before asking).

jbrennan
Note that this code needs to go in a touch-handling method for any object that is NOT the text view in question - usually that means the `touchesEnded:` method for the root UIView being handled by the view controller.
Tim
Maybe I should explain the question better. I know the call to resign the first responder. The problem is there isn't a suitable delegate method that gets called when the UITextView loses focus.
tuzzolotron
Tim,That's what I suspected. I implemented some code with to detect touches outside the TextView. This seems like an incredibly hacky way to to do things but if that's what Apple wants us to do...
tuzzolotron
jbrennan: that doesn't address his question, you are simply giving one step, not the initial testing if the touch is on the textfield or outside of it.
Garrett
+1  A: 

In my view:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];

// pass touches up to viewController
[self.nextResponder touchesBegan:touches withEvent:event];

}

In my viewcontroller:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if (keyboardShown && [touch view] != self.TextView) 
    {
         [self.TextView resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];

}

- (void)keyboardWasShown:(NSNotification*)aNotification

{
keyboardShown = YES; }

tuzzolotron
Does this work, or are you asking us to look at the code?
Garrett
This is the solution I implemented. It works.
tuzzolotron
How do I add the touchesBegan method to a UITableView that I've made a subview of self.view of the UIViewController I'm working in. Do I have to subclass UITableView, i.e., @interface TouchableTableView : UITableView? Or, is there an easier way to do it w/o subclassing UITableView?
MattDiPasquale
+3  A: 

Simplifying tuzzolotron's answer: Where the following outlet is properly connected in your xib

    IBOutlet UITextView *myTextView;

Use this in the view controller:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([myTextView isFirstResponder] && [touch view] != myTextView) {
        [myTextView resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

A tap on the View Controller's View, outside of the Text View, will resign the first responder, closing the keyboard.

ohhorob