简体   繁体   中英

How to Get the height of String text in each row of tableview cell?

Data is coming from api and i want to increase the cell height according to the height of text coming from api. I want to show more text in my label, but it cuts of because of small cell.

在此处输入图片说明

I did UItableViewAutomationDimenension , but it didn't exactly work for me.

Please tell me if anyone knows. Thanks in Advance

func heightForText(string: String, width: CGFloat, font: UIFont) -> CGFloat {
    let attrString = NSAttributedString(
        string: string,
        attributes: [NSFontAttributeName: font])
    let size = attrString.boundingRect(
    with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), 
    options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
    return size.height
}

After doing some work on this, I found the solution.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if msg1[indexPath.row].messageType == "image"{
            return 185.0
        }
        else{
            let attrString = NSAttributedString(
                string: msg1[indexPath.row].message!,
                attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)])
            let size = attrString.boundingRect(
                with: CGSize(width: 200, height: CGFloat.greatestFiniteMagnitude),
                options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)

            return size.height + 35
        }

So it gives a result output like this:

在此处输入图片说明

Anyway Thanks to all for your Answers...!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM