将键盘布局更改为表情符号

时间:2012-07-08 11:24:30

标签: ios uikit uikeyboard emoji uikeyboardtype

当UITextField成为第一个响应者时,是否可以将键盘布局更改为表情符号?或根据用户操作,如点击UIButton

我知道我可以将键盘布局更改为其中一个

typedef enum {
UIKeyboardTypeDefault,                // Default type for the current input method.
UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).

UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated

} UIKeyboardType;

我想知道是否有办法对表情符号布局做同样的事情

2 个答案:

答案 0 :(得分:14)

创建一个UITextField的子类,如下所示:

class EmojiTextField: UITextField {

    override var textInputMode: UITextInputMode? {
        for mode in UITextInputMode.activeInputModes {
            if mode.primaryLanguage == "emoji" {
                return mode
            }
        }
        return nil
    }
}

在IB中,选择此类作为自定义类来代替UITextField。

这使得键盘在字段成为第一响应者时选择表情符号键盘(如果可用)。当然,用户可以随时将键盘更改回任何其他内容,但至少它会初步选择您想要的内容。

答案 1 :(得分:3)

我已经设法防止用户切换键盘!

使用该线程iOS: How to detect keyboard change event作为配料。

完整解决方案:

class EmojiTextField: UITextField {

       // required for iOS 13
       override var textInputContextIdentifier: String? { "" } // return non-nil to show the Emoji keyboard ¯\_(ツ)_/¯ 

        override var textInputMode: UITextInputMode? {
            for mode in UITextInputMode.activeInputModes {
                if mode.primaryLanguage == "emoji" {
                    return mode
                }
            }
            return nil
        }

    override init(frame: CGRect) {
            super.init(frame: frame)

            commonInit()
        }

        required init?(coder: NSCoder) {
            super.init(coder: coder)

             commonInit()
        }

        func commonInit() {
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(inputModeDidChange),
                                                   name: UITextInputMode.currentInputModeDidChangeNotification,
                                                   object: nil)
        }

        @objc func inputModeDidChange(_ notification: Notification) {
            guard isFirstResponder else {
                return
            }

            DispatchQueue.main.async { [weak self] in
                self?.reloadInputViews()
            }
        }
    }