ios - 尝试在用户向 iOS 中的 UITableView 添加行时动态增加 UITableView 的高度

标签 ios objective-c uitableview

我正在开发一个应用程序,用户可以在其中动态地向 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/

相关文章:

ios - 如何将NSUserDefaults整数与另一个整数进行比较?

objective-c - cocoa 中的单例,他们是邪恶的吗?

ios - UISearchBar Appearance 下拉时仍显示 1px 边框

ios - 为什么从 ViewController 转到 TableViewController 时我会不断收到此错误?

ios - 使用 AFNetworking 从 json 本地文件解析数据

ios - 当键盘显示一个 TextView 但没有另一个 TextView 时如何移动 View

ios - 在 iOS 上使用 RSA 公钥加密

iphone - 在应用程序购买中:应用程序处于事件状态,并且仍显示[环境:沙箱]

ios - NSDate 问题,日期应该是前一天

ios - UITableView 分隔符插入引用在 Storyboard 中不起作用