繁体   English   中英

UIViewController中动态调整大小的TableView

[英]Dynamically sized tableview in UIViewController

这可能需要一些解释。 我有一个UIViewController子类,其中包含一个标签和一个直接位于其下的表格视图(标签和其他控件是我不能使用UITableViewController子类的原因)。 由于tableview的内容是动态的,因此添加时无法直接设置其高度。 因此,我在loadView中执行以下操作:

//add the table view with no size for now
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.scrollEnabled = NO;

//now that the datasource is set, use the delegates to update the height
    [tableView layoutIfNeeded];
    [tableView setFrame:CGRectMake(0, self.y_position, 320, [tableView contentSize].height)];

//add it to my scrollview, which contains all controls in this view
    [scrollView addSubview:tableView];

到目前为止,这种方法效果很好(尽管可以听到其他想法)。

当我进入视图的编辑模式时,就会出现问题。 我想修改表视图的内容,并插入其他节和行。 到目前为止,我具有以下setEditing的实现:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated{   
    [tableView beginUpdates];
    [super setEditing:editing animated:animated];

    //insert or remove the section and row 
    NSRange range = NSMakeRange(0, 1);
    if (self.isEditing) {
        [tableView insertSections:[NSIndexSet indexSetWithIndexesInRange:range] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else {
        [tableView deleteSections:[NSIndexSet indexSetWithIndexesInRange:range] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    [nameAndIngredientsTableView endUpdates];

}

附加部分和行的添加就很好,但是由于尚未更新表格视图的底部行,因此其底部的行被切除。 我应该怎么做?

我尝试再次使用相同的代码-layoutIfNeeded,然后手动设置高度,但这似乎无济于事

我很想知道在进入和退出编辑时如何动态调整tableview的大小。

如果有更好的解决方案,我将不公开处理,但是我只能通过手动计算新高度并手动设置动画来使它起作用:

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [nameAndIngredientsTableView setFrame:CGRectMake(0, tableView.frame.origin.y, 320, tableView.frame.size.height + delta)];
    [UIView commitAnimations];

其中delta是+ x(表示插入),-x(表示删除)。 x目前是由反复试验确定的,这并不理想,但是我正在努力从tableView.rowHeight,.sectionHeaderHeight和.sectionFooterHeight派生

我假设您尝试不滚动显示所有行。 (如果您的应用程序可以滚动显示,那么最后一行被截断不是问题吧?)

解决此问题的更好方法是发挥行高。 您固定框架高度。 然后将rowHeight计算为frameHeight / NumberOfRows。

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM