当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;
我想知道是否可以对表情符号布局进行同样的操作?
* iOS13更新*
像这样创建UITextField的子类:
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
}
}
在IB中,选择该类作为UITextField的自定义类。
当字段成为第一响应者时,这将使键盘选择表情符号键盘(如果可用)。用户当然可以随时将键盘改回其他任何位置,但至少可以对您要的内容进行初始选择。
我设法防止用户切换键盘!
使用该线程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()
}
}
}