user4048334
user4048334

Reputation:

Fit textLabel in UITableViewCell

I have a UITableView cell, with some text and it is too long so I want it to be automatically resize it. Here is what I have tried:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//set colors
UIColor *garnetColor = [UIColor colorWithRed:85.0f/255.0f green:0/255.0f blue:3/255.0f alpha:1.0];
UIColor *garnetOffSetColor = [UIColor colorWithRed:127.0f/255.0f green:1/255.0f blue:6/255.0f alpha:1.0];

UIColor *uAlbanyGoldColor = [UIColor colorWithRed:175.0f/255.0f green:120/255.0f blue:40/255.0f alpha:1.0];
UIColor *uAlbanyGoldOffSetColor = [UIColor colorWithRed:190.0f/255.0f green:135/255.0f blue:40/255.0f alpha:1.0];
//    UIColor *uAlbanyPurpleColor = [UIColor colorWithRed:78/255.0f green:26/255.0f blue:128/255.0f alpha:1.0];

UIColor *RPIRedColor = [UIColor colorWithRed:158/255.0f green:8/255.0f blue:3/255.0f alpha:1.0];
UIColor *RPIRedOffSetColor = [UIColor colorWithRed:206/255.0f green:12/255.0f blue:12/255.0f alpha:1.0];

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    cell.textLabel.adjustsFontSizeToFitWidth = YES;

    }
   //more code for the cells

}

So is there another way to resize the text so it will fit?

Thanks for the help in advance.

Upvotes: 0

Views: 179

Answers (3)

iqueqiorio
iqueqiorio

Reputation: 1187

Use this

cell.textLabel.adjustsFontSizeToFitWidth = YES;

Upvotes: 1

Alexander Krasikov
Alexander Krasikov

Reputation: 56

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   CGSize maximumCellSize = CGSizeMake(maximumCellWidth, maximumCellHeight);  // (200, 1000) for example
   CGRect textRect = [textToShow boundingRectWithSize:maximumCellSize
                                        options:(NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{NSFontAttributeName:[UIFont fontWithName:@"System" size:15]} // attributes of textToShow
                                        context:nil];
    return textRect.size.height + sumOfHeightsOfOtherConstantStuffInCell;
}

Upvotes: 0

Kuntal Gajjar
Kuntal Gajjar

Reputation: 802

adjustsFontSizeToFitWidth will not works for you.

You need to use heightForRowAtIndexPath method. Below is the sample of that method.

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

float cellHeight = [STRING_THAT_YOU_WANT_TO_DISPLAY sizeWithFont:COMMENT_FONET_NEW constrainedToSize:CGSizeMake(contentWidth - 65 - 10 - 10, 400)].height;

return cellHeight ;

}

Hope it works for you :)

Upvotes: 0

Related Questions