如何确保只能在文本字段 SwiftUi 中输入表情符号 [英] How to make sure that only emoji can be entered in the textfield SwiftUi

查看:30
本文介绍了如何确保只能在文本字段 SwiftUi 中输入表情符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found this code on the Internet and I don't know how to apply it

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
    }
}

推荐答案

您可以使用这个链接来显示表情符号键盘.

You can use this link to show the emoji keyboard.

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

I just used this class and create one string extesion to filter and get the only emojis.

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

I also, add the code for how you limit to enter emoji.

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)
    }
}

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))
                     */
                })
        }
    }
}

这篇关于如何确保只能在文本字段 SwiftUi 中输入表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆