Onichan
Onichan

Reputation: 4526

Dismiss Keyboard with inputAccessoryView

The textview is docked at the bottom (like the messages app). However, the keyboard wont dismiss when the user taps outside the textView.

import UIKit
class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var commentBar: UIView!

    @IBOutlet var commentTextField: UITextField!

    override var inputAccessoryView: UIView {
        return commentBar
    }

    override func canBecomeFirstResponder() -> Bool {
        commentBar.removeFromSuperview()
        return true
    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
        self.view.endEditing(true);
        return false;
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true);
        commentTextField.resignFirstResponder()
    }

Upvotes: 0

Views: 918

Answers (2)

Ahmad Nawaz
Ahmad Nawaz

Reputation: 1

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   self.view.endEditing(true)
   return true
}

Upvotes: 0

Britto Thomas
Britto Thomas

Reputation: 2120

No need to remove your commentBar at canBecomeFirstResponder Method. This will call each time keyboard resign.

Try some thing like this.

class ViewController: UIViewController {
@IBOutlet var commentBar: UIView!
@IBOutlet var commentTextField: UITextField!

override func viewDidLoad() {
       super.viewDidLoad()
       commentBar.removeFromSuperview()
    }
override var inputAccessoryView: UIView {
       return commentBar
    }

override func canBecomeFirstResponder() -> Bool {
       return true
    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
       self.view.endEditing(true);
       return false;
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
      self.view.endEditing(true);
      commentTextField.resignFirstResponder()
    }

}

Upvotes: 1

Related Questions