如何在ios中动态增加UITableView行高?

时间:2014-12-11 11:06:54

标签: ios xcode uitableview

我有一个要求,比如当我添加更多数据时,UITableview行高必须动态增加。喜欢

_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"]];

我写的代码就像...... ..

- (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;

}

但如果我添加额外的数据,它不会增加行高。我不知道我在哪里犯了错误。任何人都可以帮助我

3 个答案:

答案 0 :(得分:0)

如果你想根据字符串的大小进行更改,就这样做:

- (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;
}

希望这有帮助!

答案 1 :(得分:0)

使用

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

   return 140;
}

更改单元格的高度。

答案 2 :(得分:0)

如果您需要支持iOS7,并且有很多项目会影响身高。 由于有很多项目(或一些动态大小的项目),高度不容易计算。

我会调用协议方法来更新高度。

排名:

  • 易于改变高度
  • 没有恼人的计算

缺点:

  • 内存消耗
  • 您可能会看到UITableView更新。

    @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;
    }
    

我在我的Cell中做了什么(里面有一个webview):

- (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];
}