首页 > 学院 > 开发设计 > 正文

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

2019-11-14 17:59:28
字体:
来源:转载
供稿:网友

写一个方法来继承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=projectText.textSizeWithFont(UIFont.systemFontOfSize(14), constrainedToSize:CGSizeMake(100, 200))

        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);

 

 

 

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表