美文网首页
UILabel加载富文本

UILabel加载富文本

作者: King_Liu | 来源:发表于2017-02-22 10:59 被阅读62次

    因为在项目中要用到一串数字,且小数点前后的数字大小不同,所以用到了富文本。直接上代码:

    //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


    效果图

    相关文章

      网友评论

          本文标题:UILabel加载富文本

          本文链接:https://www.haomeiwen.com/subject/dygpwttx.html