Dynamic Height Calculation of UITableViewCell depend upon TextView's height

若如初见. 提交于 2019-12-12 05:48:19

问题


I have given the leading and trailing to textview inside content of tableview . I want to dynamically calculate the height of Tableviewcell. the height calculation is working fine sometimes but sometimes not working particular devices like 5c.

i have used following code to estimate the height of text :

func estimateFrameForText(text: String) -> CGRect {
    let size = CGSize(width: self.view.frame.size.width, height: 10000000)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.init(name: FontStyle.FontName.kDefault, size: 15.0)!], context: nil)
}

The important thing here is the text is HTML text, I have converted it into plain text. then that plain text is passed to above functions.


回答1:


  1. Give top,bottom,leading and trailing to textview inside content of tableview cell.
  2. Disable the scrolling of textview. Then and then, this method works. It is generally used in chat cells, wherein we want the property of automatic Data detection of links, phone numbers minus the scrolling of uitextview.
  3. Set automatic row height calculation using below methods of table view

    func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat
    {
       return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
    
    {
       return 100
    }
    



回答2:


-(CGSize) sizeForStirngInFrameSize:(CGSize)viewSize withFont:(UIFont *)font{
CGSize stringSize = [self boundingRectWithSize:CGSizeMake(viewSize.width, viewSize.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: font} context:nil].size;
return stringSize;
}

I created this method to find height for my UI label and UITextView, you can use same to calculate height for your textview and return in heightForRowAt... delegate method.

Make sure you pass proper viewSize and same Fonts. And constraints.

Thanks




回答3:


override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print(textView.contentSize.height)
}


来源:https://stackoverflow.com/questions/42431242/dynamic-height-calculation-of-uitableviewcell-depend-upon-textviews-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!