UIInputViewController为基础的自定义键盘

iOS8系统中开放了自定义输入法。主要是用UIInputViewController来创建自定义的键盘。自定义键盘的界面放在UIInputVieController的inputView属性中。

Xcode6提供了一个建立自定义键盘的入口---自定义键盘目标模版。


自定义键盘的基本数据结构如下:


自定义的输入法模板包含一个UIInputViewController 的子类,这个就是你的输入法的主要视图控制器。让我们看一下他的接口来熟悉一下他的实现

class UIInputViewController : UIViewController, UITextInputDelegate, NSObjectProtocol {
    
    var inputView: UIInputView!//界面UI
    
    var textDocumentProxy: NSObject { get }//UITextDocumentProxy对象
    
    var primaryLanguage: String?//主要的语言,默认英语
    
    func dismissKeyboard()//取消键盘
    func advanceToNextInputMode()//切换输入法
   
    func requestSupplementaryLexiconWithCompletion(completionHandler: (UILexicon!) -> Void)//一些列词库
}
textDocumentProxy 是实现了UITextDocumentProxy协议的对象,通过 documentContextBeforeInput 和 documentContextAfterInput能够获得插入点的文本上下文,然后分别通过insertText:deleteBackward在当前的插入点加上文字和向前删除文字。

protocol UITextDocumentProxy : UIKeyInput, UITextInputTraits, NSObjectProtocol {
    
    var documentContextBeforeInput: String! { get }
    var documentContextAfterInput: String! { get }
    
    func adjustTextPositionByCharacterOffset(offset: Int)
}
自定义键盘具有的两个重要和必须拥有的功能就是切换输入法和消除键盘,可以通过调用advanceToNextInputModedismissKeyboard实现。

以上的四个操作是自定义键盘响应的主要用户事件。

自定义键盘还可以获得系统的UILexicon: 包括通讯录的姓和名(分开的),快捷词条,系统内置的苹果产品相关的词语词库.

UIInputViewController遵守UITextInputDelegate协议,当文本区或者文本选项区变化时,通过 selectionWillChange,selectionDidChange,textWillChange 和 textDidChange事件来实现。

/* The input delegate must be notified of changes to the selection and text. */
protocol UITextInputDelegate : NSObjectProtocol {
    
    func selectionWillChange(textInput: UITextInput)
    func selectionDidChange(textInput: UITextInput)
    func textWillChange(textInput: UITextInput)
    func textDidChange(textInput: UITextInput)
}

注意:自定义的键盘必须能够对控件的UIKeyboardType属性进行变化,改变响应的视图布局。

重要的参考文献:

官方文档:https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/Keyboard.html

一个样例:https://github.com/WeHeartSwift/MorseCode

猜你喜欢

转载自blog.csdn.net/lcl130/article/details/42088691