IOS Dismiss/Show keyboard without Resigning First Responder

前端 未结 3 1043
广开言路
广开言路 2021-01-18 02:28

My application is used with a barcode scanner connected via Bluetooth. When the scanner is connected you can double tap a button on the scanner to dismiss/show the on scree

3条回答
  •  迷失自我
    2021-01-18 02:44

    I ran into this today and have found a solution. The trick is to use a secondary text field that is off-screen or hidden with a custom empty inputView set and make that field become the first responder. That field captures text from the hardware scanner while the software keyboard hides.

    However I got this working using a very similar approach and instead making the view controller itself the first responder as the scanning input view.

    Example:

    class SearchViewController: UIViewController, UIKeyInput {
    
        let searchField = UITextField()
        let softwareKeyboardHider = UIView()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addSubview(searchField)
            inputAssistantItem.leadingBarButtonGroups = []
            inputAssistantItem.trailingBarButtonGroups = []
        }
    
        override var canBecomeFirstResponder: Bool {
            return true
        }
    
        override var inputView: UIView? {
            return softwareKeyboardHider
        }
    
        var hasText: Bool {
            return searchField.hasText
        }
    
        func insertText(_ text: String) {
            searchField.insertText(text)
        }
    
        func deleteBackward() {
            searchField.deleteBackward()
        }
    }
    

    Now, when you want to hide the software keyboard make SearchViewController the first responder.

    To show the software keyboard make SearchViewController.searchField the first responder.

提交回复
热议问题