【问题标题】:Dynamically sized tableview in UIViewControllerUIViewController 中动态大小的表格视图
【发布时间】:2012-04-23 00:10:58
【问题描述】:

这可能需要一点解释。我有一个 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 大小应该看什么。

【问题讨论】:

    标签: ios cocoa-touch uitableview uiviewcontroller


    【解决方案1】:

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

        [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 派生它

    【讨论】:

      【解决方案2】:

      我假设您试图在不滚动的情况下显示所有行。 (如果您的应用可以滚动,那么最后一行被截断不是问题吗?)

      管理此问题的更好方法是使用行高。你固定框架高度。然后将 rowHeight 计算为 frameHeight/NumberOfRows。

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多