代码之家  ›  专栏  ›  技术社区  ›  s3lph

在应用程序中使用自定义InputViewController

  •  1
  • s3lph  · 技术社区  · 10 年前

    我目前的任务是iOS键盘扩展。现在,要通过应用商店审查,包含的应用必须提供一些“真实”内容。我考虑让用户在“设置”中启用键盘之前测试它。所以我的故事板看起来是这样的(缩小显示相关内容):

    └ ViewController
      └ View
        ├ TextField
        └ Keyboard Container
          └ KeyboardViewController
    

    这一切正常,键盘显示在容器中,但 textDocumentProxy 键盘视图控制器中的对象没有连接到任何东西,用户看不到他/她在键入什么。

    现在我正在寻找一种将键盘“附加”到文本字段的方法,同时将系统键盘放在一边,以便用户可以在自定义键盘上键入。

    我已经通过将以下函数附加到textfield的 editing did begin 行动

    @IBAction func editingBegan(sender: UITextField) {
        sender.endEditing(true)
    }
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   s3lph    10 年前

    我设法找到了以下解决方法:

    我创建了一个实现UITextDocumentProxy协议的类,该协议写入文本字段,并将其设置为键盘视图控制器中的附加代理:

    class ProxyWrapper: NSObject, UITextDocumentProxy {
    
        private let textField: UITextField
    
        init(textField: UITextField) {
            self.textField = textField
        }
    
        var documentContextBeforeInput: String? {
            get {
                return textField.text
            }
        }
    
        var documentContextAfterInput: String? {
            get {
                return ""
            }
        }
    
        func adjustTextPositionByCharacterOffset(offset: Int) {}
    
        func insertText(text: String) {
            let ntext = text.stringByReplacingOccurrencesOfString("\n", withString: "")
            textField.text = (textField.text ?? "") + ntext
        }
    
        func deleteBackward() {
            if let text = textField.text {
                textField.text = text.substringToIndex(text.endIndex.advancedBy(-1))
            }
        }
    
        func hasText() -> Bool {
            return textField.hasText()
        }
    
    }
    

    正如您所看到的,我只实现了一个非常简单的类(文本输入/删除仅在最后),因为我完全禁用了文本字段的用户交互,所以永远不会弹出“真正的”键盘。此外,我不允许插入换行符。

    它可能看起来有点老套,可能有更好的解决方案(请随时告诉我),但这很有效,因此我使用了它。

    推荐文章