coreDeviOS
coreDeviOS

Reputation: 1538

UILabel in UITableViewCell is not resizing with Auto-Layout?

I am using Auto-layout. In Custom UITableViewCell added a UILabel with max width. I tried lots of method so that if the text is less . It should shrink or if text is more it should increase the height of the label .

I tried making UILabel in CellForRowAtIndex , Which was bad idea for obvious reasons. Then i tried to get the CGSize with the help of Font and Width of the Label . Its shrinking but its not proper and for implementing it i have to Re-Draw the constrains . Basically the solutions i tried is not visually Appealing . Please help me with it . I have attached the picture of the present state of screen

Thanks enter image description here

Upvotes: 0

Views: 254

Answers (1)

user3999012
user3999012

Reputation:

//Array of name
NSMutableArray *nameArray;

//take outlet of height constraint in custom cell; 
@property(weak) IBOutlet NSLayoutConstraint *labelHeightConstraint;


-(void)viewDidLoad
{
_nameArray=[NSMutableArray arrayWithObjects:,@"I am using Auto-layout. In Custom     UITableViewCell added a UILabel with max width.",@"Hi I am Rohit",@"I Like To Help Society" ,nil];
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomerRatingsCell *customerRatingsCell=[tableView dequeueReusableCellWithIdentifier:@"CustomerRatingsIdentifier"];
customerRatingsCell.labelName=[_nameArray objectAtIndex:indexPath.row];
customerRatingsCell.headerLabelConstraint=[self getLabelHeight:[NSString stringWithFormat:@"%@",[_nameArray objectAtIndex:indexPath.row]]];
return CustomerRatingsCell;

}

and

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

      return [self getLabelHeight:[NSString stringWithFormat:@"%@",[_nameArray objectAtIndex:indexPath.row]]]+25 ;//plus 25 is remaining space apart from label height, if you are using the full height label equals to cell height then don't add it.

}



- (CGFloat)getLabelHeight:(NSString*)textLabel
{
    CGRect textRect = [textLabel boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:Avenir Roman size:12.0f]} context:nil];

    CGSize  expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);

    return expectedLabelSize.height;
}

Upvotes: 1

Related Questions