UICountingLabel作为文字动画的效果显示,在OC上可谓是用的最多的,今天我们讲一下在swift中的基本使用,包括swift3和swift4中如何使用UICountingLabel
想用UICountingLabel还是要先下载过来的
下载地址: https://github.com/dataxpress/UICountingLabel
UICountingLabel只支持整形和浮点数样式
因为这是用OC写的,用到swift中需要我们自己桥接一下奥,不会桥接的同学可以自行百度很多教程的
我们先看下在swift3中的效果和代码
swift3.gif理清几点基本的
1.创建(不多说了,自己可以init创建)
2.富文本下如何使用
上图
image.png上代码
var titleText: String! {
didSet{
//e.g:以字符串"10239个"为例
// subbStrs为截取当前字符串中的10239
let subbStrs = titleText?.substring(to: (titleText?.index((titleText?.startIndex)!, offsetBy: (titleText?.count)! - 1))!)
let str = titleText
let index = str?.index((str?.startIndex)!, offsetBy: (str?.count)! - 1)
//subStr为截取字符串中的(个)
let subStr = str?.substring(from: index!)
self.subStr = subStr
//UICountingLabel的富文本回调
countingLabel.attributedFormatBlock = {(_ value) in
let object = "\(Int(value))\(self.subStr!)"
let attributedStr = NSMutableAttributedString.init(string: object)
let rangeStr = object as NSString
let range = rangeStr.range(of: self.subStr!)
//swift3中根据当前range获取指定字符串,然后改变大小
attributedStr.addAttribute(NSFontAttributeName, value: UIFont.pingfangSC(size: 14), range: range)
return attributedStr
}
//下边就是基本配置UICountingLabel动画效果了,就两句话
countingLabel.format = "%d"
countingLabel.count(from: 0, to: CGFloat(Int(subbStrs!)!), withDuration: 2)
}
}
var subStr: String!
我们在看下swift4中的使用
swift4.gif实现效果是一样的,就是语法这块有一点点区别
image.png
countingLabel.attributedFormatBlock = {(_ object) in
let str = "\(Int(object))%"
let attrStr = NSMutableAttributedString.init(string: str)
let rangeStr = str as NSString
let range = rangeStr.range(of: "%")
//富文本语法这块系统做了一些改动,看着还凑合
attrStr.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 30), range: range)
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
return attrStr
}
countingLabel.format = "%d"
countingLabel.count(from: 0, to: 10239, withDuration: 2)
网友评论