如何确保 SwiftUi 文本字段中只能输入表情符号

Ale*_*sey 3 swift swiftui

我在网上找到了这个代码,不知道如何应用

\n
class EmojiTextField: UITextField {\n\n   // required for iOS 13\n   override var textInputContextIdentifier: String? { "" } // return non-nil to show the Emoji keyboard \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf \n\n    override var textInputMode: UITextInputMode? {\n        for mode in UITextInputMode.activeInputModes {\n            if mode.primaryLanguage == "emoji" {\n                return mode\n            }\n        }\n        return nil\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Raj*_*han 6

您可以使用链接显示表情符号键盘。

我只是使用这个类并创建一个字符串扩展来过滤并获取唯一的表情符号。

我还添加了如何限制输入表情符号的代码。

extension String {
    func onlyEmoji() -> String {
        return self.filter({$0.isEmoji})
    }
}

extension Character {
    var isEmoji: Bool {
        guard let scalar = unicodeScalars.first else { return false }
        return scalar.properties.isEmoji && (scalar.value > 0x238C || unicodeScalars.count > 1)
    }
}
Run Code Online (Sandbox Code Playgroud)
import Combine
struct EmojiContentView: View {
    
    @State private var text: String = ""
    @State private var isEmoji: Bool = true
    
    var body: some View {
        
        HStack{
            EmojiTextField(text: $text, placeholder: "Enter emoji", isEmoji: $isEmoji)
                .onReceive(Just(text), perform: { _ in
                    // This allow only emoji
                    self.text = self.text.onlyEmoji()
                    /*
                     //This allow only emoji and allow only 3 emoji
                     self.text = String(self.text.onlyEmoji().prefix(3))
                     */
                })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)