Last active
March 14, 2019 13:08
-
-
Save nicklockwood/10399979 to your computer and use it in GitHub Desktop.
How to put a fixed search bar in a UITableViewController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "TableViewController.h" | |
@interface TableViewController () | |
@property (nonatomic, strong) UISearchBar *searchBar; | |
@end | |
@implementation TableViewController | |
static const CGFloat topOffset = 64; // use 20 if there's no navigation bar, or zero if there's no status bar either | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, topOffset, 320, 40)]; | |
[self.view addSubview:self.searchBar]; | |
self.tableView.contentInset = UIEdgeInsetsMake(self.searchBar.frame.size.height, 0, 0, 0); | |
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.searchBar.frame.size.height, 0, 0, 0); | |
} | |
#pragma mark - Table view delegate | |
- (void)scrollViewDidScroll:(UIScrollView *)scrollView | |
{ | |
CGRect frame = self.searchBar.frame; | |
frame.origin.y = scrollView.contentOffset.y + topOffset; | |
self.searchBar.frame = frame; | |
} | |
#pragma mark - Table view data source | |
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section | |
{ | |
return 1000; | |
} | |
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; | |
if (!cell) | |
{ | |
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; | |
} | |
cell.textLabel.text = @"Hello World"; | |
return cell; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@zephiro Almost a year late...I know
class SwiftTableVC: UITableViewController {
}