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)
    }
}复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值