简体   繁体   中英

How to increase the UITableView row height dynamically in ios?

I have an requirement like the UITableview row height has to increase dynamically when i add more data..Like

_quoteArray = [@[@"For the past 33 years, I have looked in the mirror every morning and asked myself: 'If today were the last day of my life, would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row, I know I need to change something. -Steve Jobs",
                     @"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",
                     @"Innovation distinguishes between a leader and a follower. -Steve Jobs"]];

I wrote the code like…..

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

    static NSString *simpleTableIdentifier = @"NotificationCell";
     MyNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    //cell.dateLabel.text =dateDisplayStr;
    cell.teacherChangeLabel.text = _quoteArray[quoteIndex];



    return cell;
}


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

    // Calculate a height based on a cell

    static NSString *simpleTableIdentifier = @"NotificationCell";
    MyNotificationCell *cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];


    if(!cell) {
        cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:@"CustomCell"];
    }

    // Configure the cell

      int quoteIndex = indexPath.row % [quoteArray count];
      cell.teacherChangeLabel.text = quoteArray[quoteIndex];


    // Layout the cell

    [cell setNeedsLayout];

    // Get the height for the cell

    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // Padding of 1 point (cell separator)
    CGFloat separatorHeight = 1;

    return height + separatorHeight;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 140;

}

But it is not increasing the row height if I add extra data.I don't know where I did mistake.Can anyone please help me in this

If you want to change based on the size of the string just do it like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSString *text = [yourStringArray objectAtIndex:indexPath.row];
   UIFont *font = theFontSizeYourWant;

   return [self heigthWithString:text andFont:font]+30//put the +30 for personal like;
}

- (CGFloat)heigthWithString:(NSString*)string andFont:(UIFont *)font
{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]     initWithString:string];
    [attrStr addAttribute:NSFontAttributeName
                    value:font
                    range:NSMakeRange(0, [attrStr length])];
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(250, CGFLOAT_MAX)
                                        options:NSStringDrawingUsesLineFragmentOrigin |      NSStringDrawingUsesFontLeading
                                        context:nil];
    return rect.size.height;
}

Hope this helps!

Use

- (CGFloat)tableView:(UITableView *)tableView
  heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Change the height of cell based on indexpath ForEg
if([indexPath row]==0){
    return 44;
}

   return 140;
}

to change the height of a cell.

If you need to support iOS7 and there are lots of items affecting the height. As there are lots of items(or some dynamic size items), the height is not easy to calculate.

I would call a protocol method to update the height.

Pos:

  • Easy to change the height
  • No annoying calculation

Cons:

  • memory consumption
  • you may see the UITableView updating.

     @property (strong, nonatomic) NSMutableArray *loadedCellHeight; #pragma CellDelegate Methods - (void)displayHeight:(NSString*)height atIndexPath:(NSIndexPath *)indexPath { NSPredicate *filter = [NSPredicate predicateWithFormat:@"indexPath == %@", indexPath]; NSArray *filteredArray = [self.loadedHeight filteredArrayUsingPredicate:filter]; if (filteredArray.count==0) { [self.loadedAdHeight addObject:@{@"indexPath": indexPath, @"height": height}]; [self.tableView beginUpdates]; [self.tableView endUpdates]; } else { NSDictionary *originalDict = filteredArray[0]; if ([[originalDict objectForKey:@"height"] floatValue] != [height floatValue]) { [_loadedCellHeight removeObject:originalDict]; [_loadedCellHeight addObject:@{@"indexPath": indexPath, @"height": height}]; [self.tableView beginUpdates]; [self.tableView endUpdates]; } } } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row]; NSPredicate *filter = [NSPredicate predicateWithFormat:@"indexPath == %@", indexPath]; NSArray *filteredArray = [self.loadedAdHeight filteredArrayUsingPredicate:filter]; if (filteredArray.count>0) { return [filteredArray[0][@"height"] floatValue]; } return 0; } 

What I did in my Cell(there is a webview inside it):

- (void)loadAd:(NSString*)path
{
    if (_loaded) {
        return;
    }
    NSString *encodeUrl = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.url = encodeUrl;
    [self.webView setScalesPageToFit:YES];
    self.webView.contentMode = UIViewContentModeScaleAspectFit;
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodeUrl]];
    [self.webView loadRequest:request];

}

-(void)parseHtml
{
    NSString  *html = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
    NSLog(@"html:%@", html);
    NSDictionary *dict = [NSDictionary dictionaryWithXMLString:html];
    NSLog(@"parsed html:%@", [dict description]);
    NSDictionary *heightDict = [dict dictionaryValueForKeyPath:@"img.hidden"];
    NSLog(@"%@", [heightDict valueForKeyPath:@"_value"]);
    NSString *heightStr = [heightDict valueForKeyPath:@"_value"];
    NSString *height = [heightStr stringByReplacingOccurrencesOfString:@"advheight:" withString:@""] ;


    if (self.delegate && !_loaded) {
        [self.delegate displayHeight:height atIndexPath:_indexPath];
        _loaded = YES;
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self parseHtml];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM