Add subview to tableview which doesn't scroll
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 think开发者_JS百科ing 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.
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 to use a standard UIViewController
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 tonil
(self.tableView = nil
) in yourdealloc
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.
精彩评论