首页 > 解决方案 > 如何启用按音节自动断字?

问题描述

我有 html 和 css 文件来在我的应用程序中显示我的教科书。我有这个代码来做到这一点:

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")
        }

如何启用按音节自动断字?

我有:

在 2010 年 6 月
的全球
开发者大会上,
Apple 在开发者 工具国情咨文中
宣布
了 Xcode 的第 4版 。


我需要:

在 2010 年 6 月
的全球
开发者
大会上,Apple 在开发者 工具国情咨文 中
宣布
了 Xcode 的第 4 版 。



标签: htmlcssiosswiftwkwebview

解决方案


您可以为此使用段落样式:

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)

推荐阅读