iOS - 动态更改 uitableview 的高度



我想为UISearchBar创建建议,所以我添加了UITableView,我想按内容更改UITableView的高度。

当我获得数据时,我会打电话:

[self.searchTableView reloadData];

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section我正在尝试调整表格大小视图:

    CGRect bounds = [tableView bounds];
    NSLog(@"%f",tableView.contentSize.height);
    [tableView setBounds:CGRectMake(bounds.origin.x,
                                    bounds.origin.y,
                                    bounds.size.width,
                                    20 * [self.suggestionData count])];
    /*
    CGRect frame = self.searchTableView.frame;;
    frame.size.height = 20 * [self.suggestionData count];
    self.searchTableView.frame = frame;
     */

(20 表示 1 行的高度。我也尝试过tableView.contentSize.height,但它不起作用。也许需要更改故事板中的某些内容,或者当我试图找到解决方案时,我更改了一些错误的内容。我只是获得与我在故事板中设置的相同表视图的高度。谢谢

由于

UITableView扩展了UIScrollView我建议您使用以下方法来获得其边界适合其内容大小的表视图。

在特殊表视图的-init-awakeFromNib(可以扩展 UITableView 或创建类别)中,注册观察者

[self addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

,然后添加

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self && [keyPath isEqualToString:@"contentSize"]) {
        CGRect frame = self.frame;
        CGFloat currentHeight = self.contentSize.height;
        if (fabs(currentHeight - frame.size.height) > FLT_EPSILON) {
            frame.size.height = self.contentSize.height;
            self.frame = frame;
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:nil];
    }
}

请记住在-dealloc中取消注册观察者

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"contentSize"];
}

最新更新