swift计算label动态宽度和高度9159.com,这样就

作者: 编程  发布:2019-12-10

  swift计算label动态宽度和高度

 

func getLabHeigh(labelStr:String,font:UIFont,width:CGFloat) -> CGFloat {

        let statusLabelText: NSString = labelStr

        let size = CGSizeMake(width, 900)

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

        let strSize = statusLabelText.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context: nil).size

        return strSize.height

    }

    

  swift计算label动态宽度和高度9159.com,这样就可以根据后台返回的数据进行不同高度的设置了。    func getLabWidth(labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {

        let statusLabelText: NSString = labelStr

        let size = CGSizeMake(900, height)

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

        let strSize = statusLabelText.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context: nil).size

        return strSize.width

    }

// 得到字符串的高度

extension UILabel{

func getTextHeight(text :String,width: CGFloat,fontSize :CGFloat = 14) -> CGFloat {

//根据text的字体大小和控件的宽度以及字体内容动态计算label的高度

let textNormal = text as NSString

func getTheHeightForLabel(font:UIFont,width:CGFloat,text:String) ->UILabel{

let size = CGSizeMake(width, 1000)

let label =UILabel()

let font = UIFont.systemFontOfSize(fontSize)

let textW = width

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

label.text= text

let strSize = textNormal.boundingRectWithSize(size, options: .UsesLineFragmentOrigin , attributes: dic as? [String : AnyObject], context: nil).size

label.font= font

return strSize.height

label.numberOfLines=0

}

let textAtt:NSDictionary= [NSFontAttributeName: font]

这样就可以根据后台返回的数据进行不同高度的设置了

let textSize:CGSize=CGSizeMake(textW,CGFloat(MAXFLOAT))

let textH:CGFloat= label.text!.boundingRectWithSize(textSize,options: .UsesLineFragmentOrigin,attributes: textAttas? [String:AnyObject],context:nil).size.height

label.frame=CGRectMake(0,0, textW, textH)

return label

}

本文由9159.com发布于编程,转载请注明出处:  swift计算label动态宽度和高度9159.com,这样就

关键词:

上一篇:没有了
下一篇:没有了