将UITableView的高度调整到与仅适合总内容大小一样高的程度
所以我有一个非常基本的问题。 我有一个view
这个UITableView
,我想这个表的高度,因为它需要是显示表中的所有行。 所以,我不想滚动,我只想要所有的行出现。 (行在数量和height
是dynamic的)。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGSize cellSize = [[[_stepsArray objectAtIndex:indexPath.row]content] sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(528.0f, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping]; return cellSize.height; }
如果有20行,表格将会非常高,但是如果只有1行,则会非常小,而其他内容将不会出现在下面19行。
如果我理解正确的话,你应该可以把每行的高度加起来,然后根据这个调整tableview高度:
CGFloat tableHeight = 0.0f; for (int i = 0; i < [_stepsArray count]; i ++) { tableHeight += [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]; } self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y, self.tableView.frame.size.width, tableHeight);
您可以在[tableView reloadData]之后立即执行此操作
这里是更简单的解决scheme:所有你需要的是在UITableView
设置sizeToFit
,它已经填充单元格。 如果你通过xib
设置delegate
和dataSource
xib
,你可以在你的viewDidLoad
方法或者viewDidAppear
中这样做:
- (void)viewDidLoad { [super viewDidLoad]; [yourTableView sizeToFit]; }
但是,如果你在代码的某个地方添加delegate
和dataSource
源,你必须在这之后加上sizeToFit
:
- (void)someMethod { [yourTableView setDelegate:self]; [yourTableView setDataSource:self]; [yourTableView sizeToFit]; }
另外,你必须在reloadTable之后执行此操作,如果你在某处执行此操作。
这将调整你的桌子的高度,这是它的细胞高度的总和!
你可以这样试试
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){ NSLog(@"%f",your_tableView.contentSize.height); } }
在Swift 3.0中
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == tableView.indexPathsForVisibleRows?.last?.row { print("\(tableView.contentSize.height)") } }
在表视图中为contentSize属性添加观察者,并相应地调整框架大小
在viewDidLoad中添加下面的代码行
[your_tableview addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];
然后在callback中:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { CGRect frame = your_tableview.frame; frame.size = your_tableview.contentSize; your_tableview.frame = frame; }
希望这会帮助你。
只需使用tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
这将解决您的问题。
在桌子上设置一个高度约束,连接到一个sockets,并将以下内容添加到您的视图控制器:
override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableViewHeightContraint.constant = tableView.contentSize.height }