美文网首页swift
【原】swift基础篇之Label自适应高度

【原】swift基础篇之Label自适应高度

作者: 紫荆逸 | 来源:发表于2017-09-20 16:16 被阅读821次

Label的使用

 let jianLabel=UILabel() 
 jianLabel.frame=CGRect(x:jianTitleLabel.frame.maxX+10,y:10,width:0,height:0)
 self.view.addSubview(jianLabel)
 jianLabel.text="text"
 jianLabel.textColor=UIColor.white
 jianLabel.font=UIFont.systemFont(ofSize: 12)
 autoLabel(laebl: jianLabel,lineHeight:6.00)

//加载自适应label
    func autoLabel(laebl:UILabel,lineHeight:CGFloat){
        laebl.numberOfLines=0
        laebl.lineBreakMode = NSLineBreakMode.byWordWrapping
        let text:String = laebl.text!//获取label的text
        laebl.attributedText = self .getAttributeStringWithString(text, lineSpace: lineHeight)
        let fontSize = CGSize(width: laebl.frame.width, height: laebl.font.lineHeight)
        let rect:CGSize = text.boundingRect(with: fontSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: laebl.font], context: nil).size;
        laebl.frame = CGRect(x:laebl.frame.origin.x,y:laebl.frame.origin.y+12,width: rect.width, height: rect.height)
        laebl.sizeToFit()
    }

设置行间距

 //设置行间距
    fileprivate func getAttributeStringWithString(_ string: String,lineSpace:CGFloat
        ) -> NSAttributedString{
        let attributedString = NSMutableAttributedString(string: string)
        let paragraphStye = NSMutableParagraphStyle()
        //调整行间距
        paragraphStye.lineSpacing = lineSpace
        let rang = NSMakeRange(0, CFStringGetLength(string as CFString!))
        attributedString .addAttribute(NSParagraphStyleAttributeName, value: paragraphStye, range: rang)
        return attributedString
    }

label高度自适应

    ///label高度自适应
    /// - Parameters:
    ///   - text: 文字
    ///   - labelWidth: 最大宽度
    ///   - attributes: 字体,行距等
    /// - Returns: 高度
    func autoLabelHeight(with text:String , labelWidth: CGFloat ,attributes : [String : Any]) -> CGFloat{
        var size = CGRect()
        let size2 = CGSize(width: labelWidth, height: 0)//设置label的最大宽度
        size = text.boundingRect(with: size2, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil);
        return size.size.height
    }
    ```

相关文章

网友评论

    本文标题:【原】swift基础篇之Label自适应高度

    本文链接:https://www.haomeiwen.com/subject/pvyosxtx.html