来自HTML的属性文本中的字符串插值(Swift 4)

时间:2018-08-11 14:09:19

标签: html swift nsattributedstring string-interpolation

我正在将应用程序中的文本显示为本地HTML文件中的属性字符串,并填充标签,因为这使我可以灵活设置格式。为什么在这种情况下通常的字符串插值不起作用,并且有解决方法?目的是允许用户提供的用户名包含在字符串中。除了在标签中显示的HTML文件中保留“(用户)”,而不是像我期望的那样插入用户名之外,它的功能很好。我仍在学习,因此,如果这是一种奇怪且不可行的处理方式,请告诉我...

这是我的代码:

class ArticleViewController: UIViewController {

    @IBOutlet weak var contentField: UITextView!

    var articleID : String = ""

    var user = UserDefaults.standard.object(forKey: "user") ?? "user"

    override func viewDidLoad() {
        super.viewDidLoad()

        if let html = Bundle.main.path(forResource: "\(articleID)", ofType: "html") {
            let urlToLoad = URL(fileURLWithPath: html)
            let data = NSData(contentsOf: urlToLoad)

            if let attributedString = try? NSAttributedString(data: data as! Data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {

                contentField.attributedText = attributedString

            }
        }
    } 
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您将不得不在(user)中查找并替换attributedString的出现。

这应该有效:

import Foundation
import UIKit

var myString : NSAttributedString = NSAttributedString(string: "Hello (user), this is a message for you")
let regex = try! NSRegularExpression(pattern: "\\(user\\)", options: .caseInsensitive)
let range = NSMakeRange(0, myString.string.count)
let newString = regex.stringByReplacingMatches(in: myString.string, options: [], range: range, withTemplate: "CJDSW18")
let newAttribuetdString = NSAttributedString(string: newString, attributes: myString.attributes(at: 0, effectiveRange: nil))
print(newAttribuetdString.string)

答案 1 :(得分:0)

为什么通常的字符串插值在这种情况下不起作用

通常的字符串插值适用于Swift源文件中的String文字,而不适用于常规文本文件或html文件的内容。

您可能需要替换属性字符串中出现的(user)。 (基本概念与Carpsen90的答案没有什么不同,但是在替换已经归属的字符串时,您需要小心。)

    if let htmlURL = Bundle.main.url(forResource: articleID, withExtension: "html") {
        do {
            let data = try Data(contentsOf: htmlURL)

            let attributedString = try NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

            //### When you want to compare the result...
            //originalText.attributedText = attributedString

            let regex = try! NSRegularExpression(pattern: "\\(user\\)")
            let range = NSRange(0..<attributedString.string.utf16.count)
            let matches = regex.matches(in: attributedString.string, range: range)
            for match in matches.reversed() {
                attributedString.replaceCharacters(in: match.range, with: user)
            }

            contentField.attributedText = attributedString
        } catch {
            // Do error processing here...
            print(error)
        }
    }

示例。

article.html:

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <i>(user)</i><b>(user)</b>
</body>
</html>

在文本视图中可以看到的内容:

Screen Image

相关问题