码迷,mamicode.com
首页 > 编程语言 > 详细

swift-自动计算字符串的宽高

时间:2015-11-06 16:06:46      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

写一个方法来继承String

//自动控制文字换行及宽度

extension String {

    func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize {

        var textSize:CGSize!

        if CGSizeEqualToSize(size, CGSizeZero) {

            let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)

            textSize = self.sizeWithAttributes(attributes as! [String : AnyObject] as [String : AnyObject])

        } else {

            let option = NSStringDrawingOptions.UsesLineFragmentOrigin

            let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)

            let stringRect = self.boundingRectWithSize(size, options: option, attributes: attributes as! [String : AnyObject] as [String : AnyObject], context: nil)

            textSize = stringRect.size

        }

        return textSize

    }

}

用法:

   let projectText="我是一段字符串,来计算我的高度吧";

        let projectSize=sizeWithText(projectText, maxSize: CGSizeMake(150,20), font: UIFont.systemFontOfSize(14));

        let comProjectW:CGFloat=projectSize.width;

        let comProjectH:CGFloat=projectSize.height;

  //记得要在计算的字符串UILable中加上

  UIlable.font=UIFont.systemFontOfSize(14);

  //显示几行

     UIlable.numberOfLines=1;

  

  UIlable.frame = CGRectMake(50, 50, comProjectW, comProjectH);

 

 

 

 

swift-自动计算字符串的宽高

标签:

原文地址:http://www.cnblogs.com/brance/p/JuniorRookie.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!