swift 根据字符串数量动态计算行高

该博客介绍了一个在Swift中根据字符串内容、宽度和字体大小动态计算文本行高的方法。通过`textHeightFromTextString`函数,可以在iOS7及以上版本中获取适应字体样式和宽度的文本高度。此外,还提供了一个`getCurrentIOS`函数来获取设备的iOS版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//MARK: - 动态 计算行高,根据字符串的实际内容的多少 在固定的宽度和字体的大小,动态的计算出实际的高度
    func textHeightFromTextString(text: String, textWidth: CGFloat, fontSize: CGFloat, isBold: Bool) -> CGFloat
    {
        
        if (getCurrentIOS() >= 7.0)
        {
            //iOS7之后
            var dict: NSDictionary = NSDictionary()
            if (isBold) {
                dict = NSDictionary(object: UIFont.boldSystemFontOfSize(fontSize), forKey: NSFontAttributeName)

            } else {
                dict = NSDictionary(object: UIFont.systemFontOfSize(fontSize), forKey: NSFontAttributeName)

            }
            
            let rect: CGRect = (text as NSString).boundingRectWithSize(CGSizeMake(textWidth, CGFloat(MAXFLOAT)), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesFontLeading, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: dict as? [String : AnyObject], context: nil)
            return rect.size.height
        } else
        {
            //iOS7之前
            
            
            return 0.0
        }
        
    }
  //MARK: - 获取版本号
    func getCurrentIOS() -> Double
    {
        
        return (UIDevice.currentDevice().systemVersion as NSString).doubleValue

    }
 //改变对应frame

        var frame = self.titleLab!.frame
        frame.size.height = textHeightFromTextString(model.title!, textWidth: self.titleLab!.frame.size.width, fontSize: 19, isBold: true)
        self.titleLab!.frame = frame




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值