问题
I'm using iOS9 XCode7 I need to change the height of cell Dynamically according to labelText Height
I have used:
self.tableView.rowHeight=UITableViewAutomaticDimension;
But it is not working for custom made cell.
sizetoFit
is removed in iOS9.
Please suggest something. Thanks
回答1:
Give your label constrains relative to the cell, top, bottom, left and right.
Than your cell size will grow with the content height.
also make your label multiline.(by setting Lines property to 0 in attribute inspector)
#pragma mark- Menu table Delegates
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
回答2:
I'm not quite sure what this sentence means (a screenshot would've helped):
"I need to change the height of cell Dynamically according to labelText Height"
So, you have a UITableViewCell
, containing a UILabel
, and want each cell in your table to have a height depending on that cell's label ?
Here's the code I use.
In my UITableViewCell
class, I'll define a static function to measure, and return the height of my .xib file:
@implementation MikesTableViewCell
...
+(CGSize)preferredSize
{
static NSValue *sizeBox = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Assumption: The XIB file name matches this UIView subclass name.
NSString* nibName = NSStringFromClass(self);
UINib *nib = [UINib nibWithNibName:nibName bundle:nil];
// Assumption: The XIB file only contains a single root UIView.
UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];
sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
});
return [sizeBox CGSizeValue];
}
@end
Then, in my UIViewController
class, I'll tell my UITableView
to use this cell, find out it's height.
@property (nonatomic) float rowHeight;
UINib *cellNib = [UINib nibWithNibName:@"MikesTableViewCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomerCell"];
rowHeight = [MikesTableViewCell preferredSize].height;
...
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return (float)rowHeight;
}
Again, this might not be exactly what you're looking for, but I hope this helps.
回答3:
try this. it is so simple.
set this height in heightForRowAtIndexPath method
float vendorNameHeight = [vendorNameLbl.text heigthWithWidth:width andFont:[UIFont fontWithName:@"Signika-Light" size:21.0]];
then
UILabel*vendorNameLbl=[[UILabel alloc]initWithFrame:CGRectMake( 13, 11, 100, 22)];
vendorNameLbl.numberOfLines = 0;
[vendorNameLbl sizeToFitVertically];
来源:https://stackoverflow.com/questions/37022387/ios-dynamic-height-for-uitableviewcell