swift 富文本 获取文本size

var attributeString = NSMutableAttributedString(string:"welcome to hangge.com")

//从文本0开始6个字符字体HelveticaNeue-Bold,16号
attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,
    range: NSMakeRange(0,6))
//设置字体颜色
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(),
    range: NSMakeRange(0, 3))
//设置文字背景颜色
attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(),
    range: NSMakeRange(3,3))
label.attributedText = attributeString
 
//=======获取文本size=========

+ (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize

{

    NSDictionary *dict = @{NSFontAttributeName : font};

    CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;

    return size;

}

posted @ 2016-08-17 17:04  ReHo  阅读(1408)  评论(1编辑  收藏  举报