简体   繁体   中英

Swift: how to adapt UITableViewCell height to a UITextView inside it

这是最简单的方法,既可以使UITextView高度适应其内容,又可以使充当容器的UITableViewCell高度适应于与该UITextView相同的高度?

Set your UITextView number of line to 0. In the viewDidLoad of your Controller that contains the tableView use :

 tableView.estimatedRowHeight = 55.0
 tableView.rowHeight = UITableViewAutomaticDimension

To calculate the height of your textview, i think you need to know the height of the text. So on your heightForRowAtIndexPath delegate method, calculate the text height and return it using this:

func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

    return boundingBox.height
}

You need to set the textview constrains, bottom, top, leading and trailing to 0, so they adjust to the size of the cell. The code was taken from here .

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