How to add Storyboard headerview to tableview created at initialization by UITableViewController

时间:2015-09-14 16:10:09

标签: ios objective-c uitableview xcode6 interface-builder

I have a subclass of UITableViewController.

By default, it creates a UITableView when it is initialized. To that tableview I have set a header that I created in Interface Builder in the screen that is controlled by the controller. The header has two buttons:

one to enter editing mode for the tableview (called "Edit")

one to add a random item to the tableview (called "New").

I linked an IBOutlet property called headerView to the header from Interface Builder and I set it to be the header of the UITableView created at initialization in the viewDidLoad method.

The problem is that when I press the "New" button (which adds a new row with a new item to the tableview) the header of the tableview falls down to the bottom of the tableview.

Any idea why? How can I make it stick to the top?

This is the viewDidLoad method:

- (void)viewDidLoad {
        [super viewDidLoad];
        [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        [self.tableView setTableHeaderView:self.headerView];
    }

This is the method that gets executed when the "New" button is pressed:

- (IBAction)addNewItem:(id)sender {
    Item *newItem = [[ItemStore sharedStore] createItem];
    NSInteger lastRow = [[[ItemStore sharedStore] allItems] indexOfObject:newItem];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lastRow inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];

}

From this point the header stays at the bottom of the tableviewThis is a screenshot of the header when the tableview is empty

Thanks.

1 个答案:

答案 0 :(得分:0)

可能您以错误的方式设置了表头视图的布局。它有任何布局约束吗?

顺便说一句,this project on GitHub是一个非常简单的例子,用于演示如何在故事板中实现您想要的内容。它将产生如下结果:

enter image description here

请使用此项目与您当前的配置进行比较。 我希望这有助于这种或那种方式。