因?yàn)樵陧?xiàng)目中要用到一串?dāng)?shù)字,且小數(shù)點(diǎn)前后的數(shù)字大小不同,所以用到了富文本钦椭。直接上代碼:
//MARK:- 獲取富文本
func getattributedWithString(string:String) -> NSMutableAttributedString {
let attributeString = NSMutableAttributedString(string:string)
let stringArray = string.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "."))
attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18),range: NSMakeRange(0,stringArray[0].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)+1))
attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14),range: NSMakeRange(stringArray[0].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)+1,stringArray[1].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)))
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 102.0/255.0, green: 102.0/255.0, blue: 102.0/255.0, alpha: 1.0),range: NSMakeRange(0, stringArray[0].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)+1))
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 1.0),range: NSMakeRange(stringArray[0].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)+1, stringArray[1].lengthOfBytesUsingEncoding(NSUTF8StringEncoding)))
return attributeString
}
使用時(shí)直接傳入一個(gè)字符串返回NSMutableAttributedString
效果圖