UIViewController中动态大小的tableview

时间:2012-04-23 00:10:58

标签: ios cocoa-touch uitableview uiviewcontroller

这可能需要一些解释。我有一个UIViewController子类,它直接包含一个标签和一个tableview(标签和其他一些控件是我不能使用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的大小。

2 个答案:

答案 0 :(得分:0)

如果有更好的解决方案,我会保持开放状态,但我只能通过手动计算新高度并手动设置动画来实现这一点:

    [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

中导出它。

答案 1 :(得分:-1)

我假设你试图在不滚动的情况下显示所有行。 (如果您的应用程序滚动正常,那么最后一行切断不是问题吗?)

管理此方法的更好方法是使用行高。您修复了框架高度。然后将rowHeight计算为frameHeight / NumberOfRows。

希望这有帮助