因为在项目中要用到一串数字,且小数点前后的数字大小不同,所以用到了富文本。直接上代码:
//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
}
使用时直接传入一个字符串返回NSMutableAttributedString