在iOS7/iOS8中设置UILabel文本样式的最简单方法

90i*_*ion 3 objective-c ios swift

我正在学习一点点写一个iPad应用程序.我大部分都做了一些html5/php项目,并在大学学习了一些python.但真正让我感到震惊的一件事就是在一个客观的C标签中设计一些文字是多么困难.

也许我来自一个懒惰的降价代,但是真的,如果我想让UILabel看起来像:

目标:从线段AB 构造等边三角形.

在降价时,这很简单:

**Objective:** Construct an *equilateral* triangle from the line segment AB.

真的没有无痛苦的客观C方式来做到这一点吗?我读过的所有教程都希望我写出15行代码.对于像这样简单的事情.

所以我的问题是,如果你的应用程序中有很多样式,那么最简单的方法是什么?在iOS8中,样式文本会变得更加自然吗?

aka*_*kyy 8

您可以使用NSAttributedStringdata:options:documentAttributes:error:初始化程序(首先在iOS 7.0 SDK中提供).

import UIKit

let htmlString = "<b>Objective</b>: Construct an <i>equilateral</i> triangle from the line segment AB."
let htmlData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)

let options = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
var error : NSError? = nil

let attributedString = NSAttributedString(data: htmlData, options: options, documentAttributes: nil, error: &error)

if error == nil {
    // we're good
}
Run Code Online (Sandbox Code Playgroud)

注意:您可能还希望NSDefaultAttributesDocumentAttributeoptions字典中包含选项以提供其他全局样式(例如告诉不要使用Times New Roman).

有关更多信息,请查看NSAttributedString UIKit Additions Reference.

  • 我无法让`NSDefaultAttributesDocumentAttribute`与`NSHTMLTextDocumentType`一起使用.是否有一些技巧可以使它工作,或者它只适用于`NSPlainTextDocumentType`? (2认同)