我正在开发一个应用程序,用户可以在其中动态地向 UITableView 添加行。这部分工作正常。但是,在我的 iOS 屏幕上,无论有多少行,UITableView 都是静态高度。一旦行数增加超过某个点,用户必须滚动才能看到额外的单元格。
我想做的是随着用户添加的每一行动态增加表格的高度。因此,例如,如果我有一个 tableView,如果用户添加一行,我希望 tableview 的高度为 50px,如果用户添加 2 行,则表的高度会动态增加到 100px,直到达到最大值高度为 250px。我动态添加行的代码如下:
- (IBAction)addRow:(id)sender {
NSString *theObjectToInsert = [NSString stringWithFormat:@"Row #: %lu", (unsigned long)[self.tableData count]];
[self.tableData addObject:theObjectToInsert];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.choiceTable insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.choiceTable scrollToRowAtIndexPath:newPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
如何将 UITableView 的动态增长与行数的增加结合起来?
最佳答案
需要说明的是,如果您说现在桌面高度是静态设置的,我会假设这是不需要的,您确实希望它是动态的。
如果建议您在每次添加行时检查所有已添加行的高度。您可以通过调用已在 UITableViewDataSource
协议(protocol)中实现的方法来实现。
CGFloat maxDynamicTableHeight = 250.0f;
NSInteger numberOfSections = [self numberOfSectionsInTableView:self.tableView];
CGFloat runningHeight = 0.0f;
for (int section = 0; section < numberOfSections && runningHeight < maxDynamicTableHeight; section++) {
NSInteger numberOfRows = [self tableView:self.tableView numberOfRowsInSection:section];
for (int row = 0; row < numberOfRows && runningHeight < maxDynamicTableHeight; row++) {
runningHeight += [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
}
}
CGRect frame = self.tableView.frame;
frame.size.height = (runningHeight > maxDynamicTableHeight) ? maxDynamicTableHeight : runningHeight;
Self.tableView.frame = frame;
抱歉,如果有任何明显的问题,我在移动设备上,所以我现在无法测试。
关于ios - 尝试在用户向 iOS 中的 UITableView 添加行时动态增加 UITableView 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071508/