How to handle Curly Quotes (Smart Punctuation) on the iOS keyboard?
Few days back I faced a unique problem while adding validations for a textfield.
The task was to allow only a specific set of special characters like single quote, plus, Ampersand, etc.
But the problem arises when a user types a single quote on iPhone keyboard it was getting converted to curly quote & this was breaking the validation added.
Possible solutions came to our mind:
- Allow curly quotes along with other desired special characters.
Extra work would have been needed on frontend as well as backend since check was added to allow straight quotes & not curly quotes.
2. Replace single or double curly quotes with straight quotes at front end.
We were trying to find a way to somehow disable these curly quotes and after reading about it we came to know about Smart Punctuation in iOS.
Smart Punctuation
With iOS 11, Apple introduced Smart Punctuation. By default, this feature automatically converts straight quotes to curly quotes, in addition to converting two hyphens (–) to an em dash ( — ).
In the case of quotes, it also replaces the straight apostrophes and quotes with language-specific glyphs.
Though it makes text look typographically nicer but breaks data entry while typing user ids, passwords, etc.
To disable this auto-conversion on iPhone:
- Open the “Settings” app
- Go to “General” and then go to “Keyboards”
- Locate the setting for “Smart Punctuation” and turn that to the OFF position
How to disable this programmatically?
smartQuotesType
We can use this property to configure whether UIKit replaces straight apostrophes and quotation marks with region-specific glyphs.
The default value of this property is UITextSmartQuotesType.default, which selectively enables smart quotes based on the keyboard type.
To disable smart punctuation for any textfield or textview:
textField.smartQuotesType = UITextSmartQuotesType.no;
textField.smartDashesType = UITextSmartDashesType.no
However it will only prevent the smart quote from being entered from the keyboard, users can copy and paste it into your text field.
One way to prevent this is to implement the delegate textField:shouldChangeCharactersInRange:replacementString:
and detect a curly quote and replace it with a straight quote.
Thanks for reading!!!
References: