Dismissing the keyboard in a UIScrollView

后端 未结 12 2301
醉话见心
醉话见心 2020-11-30 20:18

Alright, I have a couple of UITextFields and UITextViews inside a UIScrollView, and I\'d like to set the keyboard to disappear wheneve

12条回答
  •  情话喂你
    2020-11-30 20:50

    In Swift:

    Bit late but if anyone else is searching an answer to this problem, this is how I have gone about solving it:

    1) Create a tap gesture recognizer with a target callback method to dismiss your keyboard using resignFirstResponder on all your fields.

    2) Add the tap gesture to the scrollview.

    Here's an example:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var t1: UITextField!
        @IBOutlet var t2: UITextField!
        @IBOutlet var t3: UITextField!
        @IBOutlet var t4: UITextField!
    
        @IBOutlet var srcScrollView: UIScrollView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
    
            // prevents the scroll view from swallowing up the touch event of child buttons
            tapGesture.cancelsTouchesInView = false
    
            srcScrollView.addGestureRecognizer(tapGesture)
        }
    
        func hideKeyboard() {
            t1.resignFirstResponder()
            t2.resignFirstResponder()
            t3.resignFirstResponder()
            t4.resignFirstResponder()
        }
    }
    

提交回复
热议问题