RxSwift之UI控件Label扩展的使用

一、将数据绑定到 text 属性上(普通文本)

  • 当程序启动时就开始计时,同时将已过去的时间格式化后显示在 label 标签上:
// 创建文本标签
let label = UILabel(frame:CGRect(x:20, y:40, width:300, height:100))
self.view.addSubview(label)
 
// 创建一个计时器(每0.1秒发送一个索引数)
let timer = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
 
// 将已过去的时间格式化成想要的字符串,并绑定到label上
timer.map{ String(format: "%0.2d:%0.2d.%0.1d",
                  arguments: [($0 / 600) % 600, ($0 % 600 ) / 10, $0 % 10]) }
.bind(to: label.rx.text)
.disposed(by: disposeBag)
  • 运行效果如下所示:

在这里插入图片描述

二、将数据绑定到 attributedText 属性上(富文本)

  • 和上例一样,只是修改分和秒这部分的文字样式,以及背景色:
// 将数字转成对应的富文本
func formatTimeInterval(ms: NSInteger) -> NSMutableAttributedString {
    let string = String(format: "%0.2d:%0.2d.%0.1d",
                     arguments: [(ms / 600) % 600, (ms % 600 ) / 10, ms % 10])
    // 富文本设置
    let attributeString = NSMutableAttributedString(string: string)
    // 从文本0开始6个字符字体HelveticaNeue-Bold,16号
    attributeString.addAttribute(NSAttributedString.Key.font,
                                 value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,
                                 range: NSMakeRange(0, 5))
    // 设置字体颜色
    attributeString.addAttribute(NSAttributedString.Key.foregroundColor,
                                 value: UIColor.white, range: NSMakeRange(0, 5))
    // 设置文字背景颜色
    attributeString.addAttribute(NSAttributedString.Key.backgroundColor,
                                 value: UIColor.orange, range: NSMakeRange(0, 5))
    return attributeString
}
let disposeBag = DisposeBag()
// 创建文本标签
let label = UILabel(frame:CGRect(x:20, y:40, width:300, height:100))
self.view.addSubview(label)
 
// 创建一个计时器(每0.1秒发送一个索引数)
let timer = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
 
// 将已过去的时间格式化成想要的字符串,并绑定到label上
timer.map(formatTimeInterval)
.bind(to: label.rx.attributedText)
.disposed(by: disposeBag)
  • 效果如下:

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╰つ栺尖篴夢ゞ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值