如何编辑 NSAttributedString 的属性?
How do I edit the attributes of an NSAttributedString?
我希望能够编辑从我的 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
}
}
要正确访问属性,您应该使用 NSMutableAttributeString
。
将您的字符串实例化为此:
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))
这只是一个示例,您可以根据需要创建自己的属性。
我希望能够编辑从我的 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
}
}
要正确访问属性,您应该使用 NSMutableAttributeString
。
将您的字符串实例化为此:
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))
这只是一个示例,您可以根据需要创建自己的属性。