Reputation: 554
What is a good way to dismiss this keyboard when the user touches outside of it? I tried the touches began method but this does not work. The textfieldshouldreturn method works okay though. I can't think of any other ways of doing this. Can someone please help me out here I would really appreciate any help. Thanks
import UIKit
var courseCatalog : [String] = Array<String>()
class HomeViewController: UIViewController, UITextFieldDelegate , UITableViewDelegate{
@IBOutlet var searchTextField: UITextField!
override func viewDidLoad() {
courseCatalog = ["Accounting", "Administration" , "American Studies" , "Anthropology" , "Arabic" , "Art" , "Aerospace Studies" , "American Sign Language" , "Biology" , "Child Development" , "Chemistry" , "Chinese" , "Criminal Justice", "Communication Studies" , "Computer Science", "Computer Engineering"]
super.viewDidLoad()
println(PFUser.currentUser())
println("Home Tab View Controller")
searchTextField.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseCatalog.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = courseCatalog[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.searchTextField.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
searchTextField.resignFirstResponder()
return true
}
}
Upvotes: 2
Views: 2826
Reputation: 921
You can try this code:
func textFieldShouldReturn(textField: UITextField) -> Bool{
textField.resignFirstResponder()
return true
}
This will dismiss the keyboard when the 'return' button is pressed on the keyboard.
Hope this can help you.
Upvotes: 0
Reputation: 25525
If your background is a UIView, you can change it to a UIControl in the identity inspector and send it to an action that resigns the first responder.
Since your background is a UITableView you should add a rightBarButtonItem to your navigationBar like 'Cancel' or 'Done' and send it to a method that resigns first responder*.
*Your first responder is the field the user is typing in.
[textField resignFirstResponder];
Swift:
textField.resignFirstResponder();
Upvotes: 2
Reputation: 8576
You should add a tap gesture recognizer to your table view that closes the keyboard when it's fired:
//Somewhere in setup
UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
viewTap.cancelsTouchesInView = FALSE;
[myTableView addGestureRecognizer:viewTap];
//Somewhere else in your class
-(void)closeKeyboard {
[self.view endEditing:TRUE];
}
Upvotes: 4