Monday, March 5, 2018

Using soft hyphens in Swift 3.0

There can be cases when we will need to support hyphens in the iOS app. But it can be crucial thing to detect at which place we should put hyphen and then break the line.

Instead of detecting places manually and creating the wheel again we can use Soft Hyphens. The logic behind it is to use unicode value of soft hyphen and put it at every possible place where the word can be split.

Lets grab the example, the sentence "I love singing" can be split "I lo-ve sing-ing". So instead of hyphens we will use \u{00AD} unicode characters.


let loveSinging = "I lo\u{00AD}ve sing\u{00AD}ing"

After having the correctly formatted string just assign the string to your label. iOS operating system will decide on its own to show/hide the unicode characters which represents hyphen. Do not forget to set line break mode to truncate tail.


label.text = loveSinging

Note for .strings file

When using the resource file, the escaping character is different. So instead of \u{00AD} we should use \U00AD.

No comments:

Post a Comment

Using soft hyphens in Swift 3.0

There can be cases when we will need to support hyphens in the iOS app. But it can be crucial thing to detect at which place we should put h...