Add subview to tableview which doesn't scroll

2019-04-17 02:51发布

I'm using a UITableViewController and want to add a searchbar.

My options are [self.tableview addSubview:searchBar] or self.tableview.tableHeaderView = searchBar Both options will scroll the searchbar along the rest of the tableview, which I understand. But is there a way to lock elements up, instead of using a UIViewController or changing the frame origin on scroll? I'm thinking of a way to get above the current view hierarchy and add a subview onto that.

I tried the opposite approach, to add a view to the superview and bring that to front

[[self.tableView superview] addSubview:searchBar]; [[self.tableView superview] bringSubviewToFront:searchBar]; }

but it didn't work.

1条回答
2楼-- · 2019-04-17 03:20

UITableViewControllers are UIViewControllers that have their main view property being an UITableView. Thus this UITableView do takes all the screen.

The approach you are looking for is using a standard UITableViewController whose view is a standard UIView, and add your UISearchBar and the UITableView as a subview to it in IB.

To do this, simply:

  • Change the class of your view controller and instead mention that it conforms to the tableview-associated protocols : change @interface UITableViewController to @interface UIViewController <UITableViewDelegate, UITableViewDataSource>
  • Add a @property(nonatomic, retain) IBOutlet UITableView* tableView property to your header file, and the associated @synthesize tableView; statement in the implementation. Don't forget to set this property back to nil (self.tableView = nil) in your dealloc for good memory managment
  • Link your UITableView instance in InterfaceBuilder to this newly created IBOutlet.

Thus you still have a UITableView but this won't be the main view that takes all your screen; instead you can layout your tableView like you want and make it take only a part of your screen, and position the UISearchBar above it.

Another approach would be to use the UISearchDisplayController to manage your UISearchBar.

查看更多
登录 后发表回答