2017-03-09 18 views
1

在我的Apple TV項目中,我需要任意顯示輸入屏幕,而不需要輸入UITextField。例如,當用戶點擊UICell時。但是,我只找到使用UITextField或顯示UIAlertController的解決方案。如何顯示沒有UITextField的輸入屏幕?

於是,我寫了一個代碼波紋管(有解決方法),以顯示輸入畫面:

class ShowInput: UITextField, UITextFieldDelegate { 

    var callback: ((String) -> Void)? 

    init() { 
     super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) 
     self.delegate = self 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func textFieldDidEndEditing(_ textField: UITextField) { 
     callback?(textField.text!) 
     textField.text = "" 

     textField.removeFromSuperview() 
    } 
} 

然後,鑑於...

class CreateGridViewController: UICollectionViewController { 

    let showInput = ShowInput() 

    // ... 

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

     let cell = collectionView.cellForItem(at: indexPath) as! CellConfigInput 
     cell.addSubview(showInput) 

     showInput.callback = { text in 
      cell.labelField.text = text 
     } 

     showInput.becomeFirstResponder() 
    } 

但是,我希望有一個更好的解決方案,一個可讀的代碼。這是可能的?

回答

0

你可以使任何標準的UIResponder子類符合UIKeyInput協議,並調用becomeFirstResponder()就可以調出鍵盤。

由於UICollectionViewControllerUIResponder的子類,因此您應該可以使CreateGridViewController符合鍵輸入協議並避免整個文本字段。

+0

對不起,但我試過了,我不能工作。我對'CellConfigInput'進行了'UIKeyInput'協議的訂閱,並且重寫'canBecomeFocused'以始終返回true,但是當我調用'becomeFirstResponder()'時,什麼都不會發生。我也嘗試過使用'CreateGridViewController',但不能工作。 – Macabeus

+0

您需要重寫'canBecomeFirstResponder'而不是'canBecomeFocused'來使這個工作。 –

+0

是的,我也做了,但沒有顯示鍵盤:https://gist.github.com/brunomacabeusbr/6a196a6293bb429119d49ca2a3757080 行'cell.becomeFirstResponder()'和'override var canBecomeFocused:Bool {return true}'是稱爲,但即使如此,鍵盤也不會被調用。 – Macabeus