美文网首页swift
swift4.0 根据文字计算带emoji的文字高度

swift4.0 根据文字计算带emoji的文字高度

作者: 小曼blog | 来源:发表于2018-05-24 12:27 被阅读6次

这是一个基本的功能,实现的方法自然也很多了,仁者见仁,智者见智,若觉得我的实现不够好,欢迎指正。

效果图:


高度截图.gif 文字高度截图.png

代码实现:

//
//  TestCell.swift
//  SwiftCalculateHeight
//
//  Created by iOS on 2018/5/24.
//  Copyright © 2018年 weiman. All rights reserved.
//

import UIKit

let screenWidth = UIScreen.main.bounds.size.width

class TestCell: UITableViewCell {
    
    @IBOutlet weak var textL: UILabel!
    
    class func height(text: String) -> CGFloat {
        // 注意这里的宽度计算,要根据自己的约束来计算
        let maxSize = CGSize(width: (screenWidth - 30), height: CGFloat(MAXFLOAT))
        let paraph = NSMutableParagraphStyle()
        let textSize = NSString(string: text).boundingRect(
            with: maxSize,
            options: [.usesFontLeading, .usesLineFragmentOrigin],
            attributes: [.font : UIFont.systemFont(ofSize: 14),
                         .paragraphStyle: paraph],
            context: nil).size
        // 注意,这里的数字也是根据实际情况来的,这里的文字距离上面是10,距离下面也是10,所以加了两个10
        return textSize.height + 10 + 10
    }

}

demo地址:

https://github.com/weiman152/SwiftCalculateHeight/tree/master

相关文章

网友评论

    本文标题:swift4.0 根据文字计算带emoji的文字高度

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