Reputation: 88
I had taken two view inside content view. Height of "Post Container View" (Red background) is calculated dynamically as per height of label (All done using Autolayout).
Now I want that if height of "Post Container View" (Red background) will increase then height of cell view auto increase. I want to do this using autolayout.
I want to calculate height of UITableview cell using Autolayout. How to do it ?
Cell Height = Post Container View (Flexible as per label height)+ Image Container View Height (300 Fix)
I had seen this type of method, but dont know how to implement in my code ?
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell
{
sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.MyTableView.frame), CGRectGetHeight(sizingCell.bounds));
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 1.0f; // Add 1.0f for the cell separator height
}
Upvotes: 0
Views: 880
Reputation: 1233
Use this Extension
class for string:
import UIKit
extension String {
func sizeOfString (font: UIFont, constrainedToWidth width: Double) -> CGSize {
return NSString(string: self).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
} }
In UITableView
delegate calculate UILabel
width:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let item = "hkxzghkfjkgjkfxkj jjhghdjajfjkshgjkhkkn jhkhhgdfgjkhsfjkdghhhsxzgnfshgfhk jhsfgfhjfhghj "
let widthOfLabel = Double(view.frame.size.width) - 30
let textHeight = item.sizeOfString(UIFont.systemFont(14), constrainedToWidth: widthOfLabel)
return (padding + textHeight.height)
}
Upvotes: 0
Reputation: 1154
To calculate height of cell :
CGFloat height ; // take global variable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
height = cell.PostContainerView.frame.size.height ;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
height = height + 300 //(300 is Fix height of Image Container View ) ;
return height ;
}
Upvotes: 1
Reputation: 1519
Do you want to calculate the height, or the tableView to calculate the height itself, considering your autolayout configuration ?
To do so, don't implement the delegate method heightForRowAtIndexPath but estimatedHeightForRowAtIndexPath instead (with whatever value you want for the moment).
The tableView will determine the height of the cell considering autolayout constraints applied on it. Be warned that sometimes you need to call layoutIfNeeded on your cell, after you updated it. (for exemple in the cellForRowAtIndexPath)
Upvotes: 1