Quantcast
Channel: Active questions tagged utf-8 - Stack Overflow
Viewing all articles
Browse latest Browse all 1142

UTF-8 character limit on TextField not working properly

$
0
0

I have a text field in my app that needs its character count limited. It works fine with regular text. But I need to take into account special characters and emojis and when the textfield reaches the limit, and I delete one character, and input for example ¢ (2 bytes) or € (3 bytes) repeatedly, it behaves as if there is no character limit at all and you can input anything.

TextField("Username", text: $ame)    .onChange(of: name, perform: { value in        totalBytes = value.utf8.count        // Only mess with the value if it is too big        if totalBytes > 14 {            let firstNBytes = Data(name.utf8.prefix(14))            if let maxBytesString = String(data: firstNBytes, encoding: String.Encoding.utf8) {                // Set the message back to the last place where it was the right size                name = maxBytesString            } else {                print("not a valid UTF-8 sequence")            }        }    })

The console does print the "not valid UTF-8" warning, but the textfield is never corrected in such an edge case. Any help? BTW, "name" is a @State variable and gets initialized successfully with the onAppear method, if that matters.


Viewing all articles
Browse latest Browse all 1142

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>