一、将数据绑定到 text 属性上(普通文本)
- 当程序启动时就开始计时,同时将已过去的时间格式化后显示在 label 标签上:
let label = UILabel(frame:CGRect(x:20, y:40, width:300, height:100))
self.view.addSubview(label)
let timer = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
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)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e46e7af3f9389adce58aab48c4291a9a.png#pic_center)
二、将数据绑定到 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)
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)
let timer = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
timer.map(formatTimeInterval)
.bind(to: label.rx.attributedText)
.disposed(by: disposeBag)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ad510279bf04a01c2e2e5230c3df013e.png#pic_center)