1

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.
   } 
}
Krunal
  • 77,632
  • 48
  • 245
  • 261

2 Answers2

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() {}
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Mohammad Sadiq
  • 5,070
  • 28
  • 29
2

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.

Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92