IOS Dismiss/Show keyboard without Resigning First Responder

前端 未结 3 1042
广开言路
广开言路 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.

    0 讨论(0)
  • 2021-01-18 02:50

    To end editing completely in the view you can use the following

    [self.view endEditing:YES];
    

    This will remove the keyboard for you in the view.

    0 讨论(0)
  • 2021-01-18 02:51

    For anyone still struggling with this, you can achieve this in Swift by making the inputView of the textfield equals UIView()

    That is:

    yourtextfield.inputview = UIView()
    
    0 讨论(0)
提交回复
热议问题