如何在没有UITextField的情况下显示输入屏幕?

时间:2017-03-09 01:36:42

标签: swift apple-tv

在我的Apple TV项目中,我需要任意显示输入屏幕,而不是UITextField。例如,当用户点击UICell时。但是,我只使用UITextField或显示UIAlertController找到解决方案。

然后,我写了一个代码(带有解决方法)来显示输入屏幕:

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()
    }

但是,我希望有一个更好的解决方案,可读的代码。它有可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使您喜欢的任何标准UIResponder子类符合UIKeyInput协议,并在其上调用becomeFirstResponder()以启动键盘。

由于UICollectionViewControllerUIResponder子类,因此您应该能够使CreateGridViewController符合密钥输入协议并避免使用整个文本字段。