Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure that only emoji can be entered in the textfield SwiftUi

Tags:

swift

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
    }
}
like image 524
Alexsey Avatar asked Oct 21 '25 22:10

Alexsey


1 Answers

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))
                     */
                })
        }
    }
}
like image 116
Raja Kishan Avatar answered Oct 24 '25 07:10

Raja Kishan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!