2017-08-03 117 views
0

我需要打開鍵盤上的按鈕單擊UIButton(不使用/用於UITextField)。我試圖通過覆蓋變量canBecomeFirstResponder來創建自定義按鈕,但它不起作用。iOS - UIButton成爲第一響應者打開鍵盤

有沒有其他方法可以做到這一點?

注意:我想將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. 
    } 
} 
+0

是否要使用鍵盤來更改UIPicker顯示的數據? – Phyber

+0

@Phyber你可能知道,我們可以將UIPickerView設置爲UITextField的inputView,就像我用UIButton做的那樣 – Krunal

+0

[UIBUTTON和picker view]的可能重複(https://stackoverflow.com/questions/6429900/uibutton-and-picker-view) – dan

回答

0

像這樣添加UIKeyInput的一致性。它應該工作。

class RespondingButton: UIButton, UIKeyInput{ 
+0

好吧,讓我試試這個 – Krunal

+0

部分意思是? –

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到另一個視圖,以便能夠自定義更多。

-1

通過擴展按鈕UIKeyInputUITextInputTraits並覆蓋以下文本輸入功能,它可以被存檔。

class RespondingButton: UIButton, UIKeyInput, UITextInputTraits { 

     private var customInputView: UIView? 
     override var inputView: UIView? { 
     get { 
      return customInputView 
     } 
     set (newValue) { 
      customInputView = newValue 
     } 
    } 

    override var canBecomeFirstResponder: Bool { 
     return true 
    } 
} 
+0

缺少協議方法實現。甚至無法編譯。 – zontar

+0

@zontar你可以自己實現協議方法,這是一個樣本測試代碼作爲錯誤解決方案。你可以問,如果你需要的源代碼,而不是downvote。它的工作和我在我的項目中實現的 – Krunal

+0

如果您在沒有指定代碼丟失的情況下給出一個類實現,對我來說這可能是或者可能不是微不足道的,對我來說這是一個倒退。如果它們微不足道,那就實施它們,如果不是的話,評論暗示要做什麼。如果它正在工作,請給出更好的說明。就這一點而言,我已經恢復使用帶有一行解決方法的UITextField。 – zontar

相關問題