10. Set the cell height (when the label height is variable, the cell height is variable) and celllabel
First: (available after iOS8)
In Xib or stroyboard (the code can also be used)
Use AutoLayout to set the label constraint (for example, you can set four sides to 50 from the screen, and the four sides must be fixed ).
In the Code Section:
Estimate the cell height and set the cell height to automatically adjust the size. The Code is as follows:
1 self. tableView. estimatedRowHeight = 44; // It's Okay To write this value, but there must be 2 self. tableView. rowHeight = UITableViewAutomaticDimension;
Method 2: boudingRectWithSize
When setting the label constraint, you only need to set up the upper left and right directions as needed.
Then obtain the label text and call the boudingRectWithSize method.
1 // maximum text size 2 CGSize maxSize = CGSizeMake ([UIScreen mainScreen]. bounds. size. width-40, MAXFLOAT); 3 // maximum text height 4 CGFloat textH = [self. text boundingRectWithSize: maxSize options: NSStringDrawingUsesLineFragmentOrigin attributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 14]} context: nil]. size. height;