咱們經常看到簡單平實的文本顯示,而後確實能夠經過RichText來完成豐富文本的外觀,加強界面的表達力。javascript
UILabel等組件,除了text屬性外,還有attributedText屬性,經過構建NSAttributedString的實例,並賦值給此屬性,就能夠設置RichText了。下面是一個趁手的案例:java
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
let nav = UINavigationController()
window!.rootViewController = Page()
nav.pushViewController(HomeViewController(), animated: true)
window!.rootViewController!.view.backgroundColor = .blue
window!.makeKeyAndVisible()
return true
}
}
class Page :UIViewController{
override func viewDidLoad() {
let label = UILabel()
label.backgroundColor = .red
let attrStr = try! NSAttributedString(
data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
label.frame = CGRect(x:0,y:100,width:100,height:20)
view.addSubview(label)
let text = UITextView()
let attr2 = [NSFontAttributeName: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSForegroundColorAttributeName: UIColor.purple]
let titleString = NSAttributedString(string: "Read all about it!", attributes: attr2)
text.attributedText = titleString
text.frame = CGRect(x:0,y:200,width:100,height:200)
view.addSubview(text)
}
}複製代碼