Swift iOS : RichText

栏目: Swift · 发布时间: 6年前

内容简介:Swift iOS : RichText

我们常常看到简单平实的文本显示,然后确实可以通过RichText来完成丰富文本的外观,增强界面的表达力。

UILabel等组件,除了text属性外,还有attributedText属性,通过构建NSAttributedString的实例,并赋值给此属性,就可以设置RichText了。下面是一个趁手的案例:

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)
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

技术赋权

技术赋权

郑永年 / 邱道隆 / 东方出版社 / 2014-4-1 / CNY 45.00

在本书中,作者对中国互联网的历史做了一次突破性的研究,细致又全面地观察了中国互联网对于国家和社会的影响,发现互联网给中国的社会—政治变革带来了新的动力。政府权力和社会力量在以互联网为媒介的公共领域中转换。 从大量的数据梳理和事实分析中,作者得出了四重的研究结论。首先,互联网给政府和社会都增加了权力。互联网在促进政治自由化中扮演了重要的角色,使政府更加开放、透明和负责任。第二,互联网产生了大量......一起来看看 《技术赋权》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试