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

Swift 如何在没有UITextField的情况下显示输入屏幕?,swift,apple-tv,Swift,Apple Tv,在我的苹果电视项目中,我需要任意显示一个输入屏幕,没有UITextField。例如,当用户在UICell中单击时。但是,我只找到了使用UITextField或显示UIAlertController的解决方案 然后,我编写了下面的代码(带有解决方法)来显示输入屏幕: class ShowInput: UITextField, UITextFieldDelegate { var callback: ((String) -> Void)? init() { s

在我的苹果电视项目中,我需要任意显示一个输入屏幕,没有
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()
    }

但是,我想要一个更好的解决方案,具有可读的代码。有可能吗?

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


由于
UICollectionViewController
UIResponder
子类,您应该能够使
CreateGridViewController
符合按键输入协议并避免整个文本字段。

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


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

很抱歉,我尝试了,但无法使用它。我使用了
CellConfigInput
subscribe
UIKeyInput
协议,并覆盖
canBecomeFocused
以始终返回true,但是,当我调用
becomeFirstResponder()
时,什么也没有发生。我也试过使用
CreateGridViewController
,但不起作用。你需要覆盖
canBecomeFirstResponder
,而不是
canBecomeFocused
,才能起作用。是的,我也做了,但没有显示键盘:Line
cell.becomeFirstResponder()
覆盖变量canBecomeFocused:Bool{return true}
已被调用,但即使如此,键盘也未被调用。抱歉,我尝试过,但无法使用它。我使用了
CellConfigInput
subscribe
UIKeyInput
协议,并覆盖
canBecomeFocused
以始终返回true,但是,当我调用
becomeFirstResponder()
时,什么也没有发生。我也试过使用
CreateGridViewController
,但不起作用。你需要覆盖
canBecomeFirstResponder
,而不是
canBecomeFocused
,才能起作用。是的,我也做了,但没有显示键盘:Line
cell.becomeFirstResponder()
覆盖变量canBecomeFocused:Bool{return true}
被调用,但即使如此,键盘也没有被调用。