【问题标题】:How do I edit the attributes of an NSAttributedString?如何编辑 NSAttributedString 的属性?
【发布时间】:2015-05-28 18:23:19
【问题描述】:

我希望能够编辑从我的 api 请求中获得的 HTML,更改字体并增加其他内容。

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    var dataString:String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
    dispatch_async(dispatch_get_main_queue()) {

        var attributedString:NSAttributedString = NSAttributedString(data: data, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!

        self.textView.attributedText =  attributedString
    }
}

【问题讨论】:

  • 你必须使用NSMutableAttributedString

标签: html ios swift nsattributedstring


【解决方案1】:

要正确访问属性,您应该使用NSMutableAttributeString

将您的 String 实例更改为:

var attributedString: NSMutableAttributedString = NSMutableAttributedString(data: data, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!

并像这样添加一个属性:

mutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Avenir", size: 18.0)!, range: NSRange(location:2,length:4))

这只是一个示例,您可以根据需要创建自己的属性。

【讨论】: