Search code examples
htmlcssiosswiftwkwebview

How to enable automatic hyphenation of words by syllables?


I have html and css files to show my text book in my app. I have this code to do it:

let headerString = "<meta name=\"viewport\" content=\"initial-scale=1.1\" />"
do {
            guard let filePath = Bundle.main.path(forResource: "\(readBookNumber)", ofType: "html")
                else {
                    print ("File reading error")
                    return
                }
            var content =  try String(contentsOfFile: filePath, encoding: .utf8)
            let baseUrl = URL(fileURLWithPath: filePath)
            
            content.changeHtmlStyle(font: "Iowan-Old-Style", fontSize:  UserDefaults.standard.integer(forKey: "textSize"), fontColor: textColor)
            webView.loadHTMLString(headerString+content, baseURL: baseUrl)
        }
        catch {
            print ("File HTML error")
        }

How to enable automatic hyphenation of words by syllables?

I have:

In June 2010 at
the World Wide
Developers Conference
Apple
announced version
4 of Xcode
during the Developer
Tools State
of the Union address.

I need:

In June 2010 at
the World Wide
Developers Con-
ference, Apple
announced ver-
sion 4 of Xcode
during the Devel-
oper Tools State
of the Union ad-
dress.


Solution

  • You can use paragraph style for this:

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .left
    paragraphStyle.hyphenationFactor = 1.0
    paragraphStyle.lineBreakMode = .byWordWrapping
    let attributes = [
                      NSAttributedString.Key.paragraphStyle: paragraphStyle,
                      NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)
                     ]
    
    let attributedText = NSAttributedString(string: inputText, attributes: attributes)