swift - UICountingLabel的富文本基本使用

來源:互聯網
上載者:User
UICountingLabel作為文字動畫的效果顯示,在OC上可謂是用的最多的,今天我們講一下在swift中的基本使用,包括swift3和swift4中如何使用UICountingLabel 想用UICountingLabel還是要先下載過來的 下載地址: https://github.com/dataxpress/UICountingLabel

UICountingLabel只支援整形和浮點數樣式 因為這是用OC寫的,用到swift中需要我們自己橋接一下奧,不會橋接的同學可以自行百度很多教程的 我們先看下在swift3中的效果和代碼

理清幾點基本的

1.建立(不多說了,自己可以init建立)
2.富文本下如何使用 上圖

上代碼

    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中的使用

實現效果是一樣的,就是文法這塊有一點點區別

        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)
以上就是swift3和swift4中UICountingLabel富文本的基本使用,有任何疑問可以在下方留言奧
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.