iOS - UIButton become first responder to open keyboard

早过忘川 提交于 2019-12-11 05:38:51

问题


I need to open keyboard on button click for UIButton (not using/for UITextField). I have tried to create custom button by overriding variable canBecomeFirstResponder but it's not working.

Is there any other way to do so?

Note: I want to set UIPIckerView as an input view of UIButton in key board frame.

Here is my code.

class RespondingButton: UIButton {


    override var canBecomeFirstResponder: Bool {
        return true
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }


    private func commonInit() {
        // common init
    }



}

In my view controller, I connected button action.

class TestViewController: UIViewController {

   @IBAction func testBecomeFirstResponder(button: RespondingButton){
      button.becomeFirstResponder()  // Not working.
   } 
}

回答1:


Here is what I would do.

  1. Create transparent textField 1x1px, lets say it is myTextField.
  2. Then add your desired button. In the button action make the myTextField.becomeFirstResponder().

Create view:

let pvBackground: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
        v.backgroundColor = .white
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
}()

In viewDidLoad:

pvBackground.addSubview(yourPickerView)//add the picker into the pvBackground
myTextField.inputView = pvBackground

I added the pickerView into the another view to be able to customize it more.




回答2:


Add conformance to UIKeyInput like this. It should work.

class RespondingButton: UIButton, UIKeyInput {

    override var canBecomeFirstResponder: Bool {
        return true
    }

    var hasText: Bool = true
    func insertText(_ text: String) {}
    func deleteBackward() {}
}


来源:https://stackoverflow.com/questions/45491518/ios-uibutton-become-first-responder-to-open-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!