zoukankan      html  css  js  c++  java
  • swift-自动计算字符串的宽高

    写一个方法来继承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);

     

     

     

     

  • 相关阅读:
    close connection error java.sql.SQLRecoverableException: IO Error: Broken pipe
    Mysql 备份与恢复
    MACBOOK 破解wifi密码
    MAC 安装homebrew
    Linux(CentOS / RHEL 7) 防火墙
    ORA-01031: insufficient privileges
    Oracle登录认证
    ORA-12162: TNS:net service name is incorrectly specified
    lsnrctl: .... cannot restore segment prot after reloc: Permission denied
    CentOS / RHEL 配置yum源
  • 原文地址:https://www.cnblogs.com/brance/p/JuniorRookie.html
Copyright © 2011-2022 走看看