0

I know that to close the keyboard by touching anywhere else in Obj-C you would have to write

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

But how would you do that with Swift?

Thanks

Kevin
  • 16,696
  • 7
  • 51
  • 68
lagoon
  • 6,417
  • 6
  • 23
  • 30
  • There was this thread literally in the right hand side's "Related" column and apparently it's yours. http://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift?rq=1 –  Jun 13 '14 at 01:35
  • 1
    you want us to translate the code for you? – Bryan Chen Jun 13 '14 at 01:36
  • This will only close the keyboard if `_answerField`, whatever that is, is the first responder. What you really want is to call `endEditing:YES` on the view. – nhgrif Jun 13 '14 at 01:44

2 Answers2

1

Here's the translation:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let touch = event.allTouches().anyObject() as UITouch
    if _answerField.isFirstResponder() && touch.view != _answerField {
        _answerField.resignFirstResponder()
    }
    super.touchesBegan(touches, withEvent: event)
}

I recommend reading Apple's "The Swift Programming Language" book and looking over Apple's beta documentation involving their existing API's and how to interact with them.

David Skrundz
  • 13,067
  • 6
  • 42
  • 66
  • Thanks. XCode gives me a suggestion to change let touch = event.allTouches().anyObject() to let touch : AnyObject! = event.allTouches().anyObject() – lagoon Jun 13 '14 at 01:44
  • This will only close the keyboard if `_answerField`, whatever that is, is the first responder. What you really want is to call `endEditing:YES` on the view. Otherwise, if you have multiple text fields, this code quickly become really silly. – nhgrif Jun 13 '14 at 01:45
  • Thanks for that nhgrif. I only have one text field for this one but when I run this code, it gives me an error on ** and says use of unresolved identifier '**' and operator is an unknown binary operator – lagoon Jun 13 '14 at 01:51
  • Sorry about that. Those should be `&&` instead. I also added the cast to UITouch that was causing the other warning. – David Skrundz Jun 13 '14 at 01:51
0

You can try as alternative assign UITapGestureRecognizer (with self.view.endEditing(true) ) to parent view

Sergey Zhukov
  • 714
  • 6
  • 5