【问题标题】:iOS - UIButton become first responder to open keyboardiOS - UIButton 成为打开键盘的第一响应者
【发布时间】:2017-08-03 18:02:40
【问题描述】:

我需要在 UIButton 的按钮单击时打开键盘(不使用/用于 UITextField)。我试图通过覆盖变量canBecomeFirstResponder 来创建自定义按钮,但它不起作用。

还有其他方法吗?

注意:我想将 UIPIckerView 设置为关键板框架中 UIButton 的输入视图。

这是我的代码。

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
    }



}

在我的视图控制器中,我连接了按钮操作。

class TestViewController: UIViewController {

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

【问题讨论】:

  • 你想用键盘来改变 UIPicker 显示的数据吗?
  • @Phyber 你可能知道,我们可以将 UIPickerView 设置为 UITextField 的 inputView,方法类似,我需要使用 UIButton 来完成
  • UIBUTTON and picker view的可能重复
  • 也许这很奇怪,但隐藏的文本字段是什么,并将其设置为第一响应者 - 就像没有其他东西对你有用。
  • @Retterdesdialogs,我有这个选择,但这是我让它发挥作用的最后选择。

标签: ios swift uibutton becomefirstresponder


【解决方案1】:

这就是我要做的。

  1. 创建透明的textField 1x1px,假设它是myTextField
  2. 然后添加您想要的按钮。在按钮操作中创建myTextField.becomeFirstResponder()

创建视图:

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

viewDidLoad:

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

我将pickerView 添加到另一个视图中以便能够对其进行更多自定义。

【讨论】:

    【解决方案2】:

    像这样添加对 UIKeyInput 的一致性。它应该工作。

    class RespondingButton: UIButton, UIKeyInput {
    
        override var canBecomeFirstResponder: Bool {
            return true
        }
    
        var hasText: Bool = true
        func insertText(_ text: String) {}
        func deleteBackward() {}
    }
    

    【讨论】:

    • 部分意思?
    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多