如何动态设置UITableView的高度? [英] How to dynamically set the height of a UITableView?

查看:165
本文介绍了如何动态设置UITableView的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 heightForRowAtIndexPath:方法的不同单元格高度的tableview。

I have a tableview with different cell heights using the heightForRowAtIndexPath: method.

我想动态设置 UITableView 的高度。目前我正在使用以下方法在 viewDidLoad 方法中设置tableView的尺寸:

I would like to dynamically set the height of a UITableView. At the moment I'm setting the dimensions of the tableView in viewDidLoad method using:

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, 400)];
self.tableView.dataSource = self;
self.tableView.delegate = self;

我想也许我可以添加这个: self.tableView.contentSize.height ; 但问题当然是内容大小仅在表加载后计算,所以如果我把它放在

I thought maybe I could add this: self.tableView.contentSize.height; but the problem of course is that the content size is only calculated after the table loads, so if I put it in

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, self.tableView.contentSize.height)];

它不起作用。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *description = [photosFromCommentsArray objectAtIndex:indexPath.row];
    //   NSLog(@"description is %@",description);

    if(description == (id)[NSNull null])
    {
        return 70; 
    }
    else
    {
        return 200;
    }
}


推荐答案

添加表视图上的contentSize属性的观察者,并相应地调整框架

Add an observer for the contentSize property on the table view, and adjust the frame accordingly

[self.tableView addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];

然后在回调中:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    CGRect frame = self.tableView.frame;
    frame.size = self.tableView.contentSize;
    self.tableView.frame = frame;
}

这篇关于如何动态设置UITableView的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆