Skip to content

Instantly share code, notes, and snippets.

@jnjosh
Created June 9, 2023 21:42
Show Gist options
  • Save jnjosh/0bc6e37ee756059bea5b155b8a9998dc to your computer and use it in GitHub Desktop.
Save jnjosh/0bc6e37ee756059bea5b155b8a9998dc to your computer and use it in GitHub Desktop.
Quick UITextField » SwiftUI wrapper for textfield that forces emoji keyboard
import SwiftUI
// UIKit-based text field that forces emoji keyboard as input mode.
class UIEmojiTextField : UITextField {
override var textInputMode: UITextInputMode? {
return UITextInputMode.activeInputModes
.filter { $0.primaryLanguage == "emoji" }
.first
}
}
// Wrap UIKit-based text field in view representable to provide to SwiftUI
struct EmojiTextField : UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UIEmojiTextField {
let textField = UIEmojiTextField()
textField.text = text
textField.delegate = context.coordinator
textField.placeholder = "Enter Emoji 🙃"
return textField
}
func updateUIView(_ uiView: UIEmojiTextField, context: Context) {
uiView.text = text
uiView.reloadInputViews()
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var textField: EmojiTextField
init(_ textField: EmojiTextField) {
self.textField = textField
}
func textFieldDidChangeSelection(_ textField: UITextField) {
// probably need to do more here to limit the character set, can't prevent users
// from changing keyboards and entering text.
textField.text = textField.text ?? ""
}
}
}
struct ContentView: View {
@State var emojiText: String = ""
var body: some View {
VStack {
EmojiTextField(text: $emojiText)
}
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment