UISearchBar with hidden TableView on NavigationBar

て烟熏妆下的殇ゞ 提交于 2019-12-14 03:21:39

问题


I am trying to create a view with a searchBar on the NavigationBar, I want this searchBar to open a tableView with the search results as soon as typing begins, and hide it once an item is touched. I am new to this platform, so I need just a path to follow, I don't know where to start actually.


回答1:


According to my comment: Heres a more in depth explanation. Happy coding:

.h

@interface TableViewController : UITableViewController <UISearchBarDelegate>

@property (strong, nonatomic) UISearchBar *searchBar;

@end

.m

- (void) viewDidLoad:(BOOL)animated {

UIView *searchbarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)]; //This adds a container that will hold the search bar. 
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)]; 
self.searchBar.delegate = self;
[searchbarView addSubview:self.searchBar];
self.tableView.tableHeaderView = searchbarView; //Inserts UIView into the header of self.tableView
[self.tableView setContentOffset:CGPointMake(0, 44)];
}

And thats pretty much it. If you want to customize other things like the keyboard layout and the way text populates and the color and font and placeholder text etc, you can edit it in viewDidLoad or make a subclass

EDIT I have included some example code for customization below:

self.searchBar.keyboardAppearance = UIKeyboardAppearanceDark;
self.searchBar.returnKeyType = UIReturnKeySearch;
self.searchBar.searchBarStyle = UISearchBarStyleProminent;
self.searchBar.barTintColor = [UIColor lightGrayColor];
self.searchBar.placeholder = @"Search for queries here";
self.searchBar.showsCancelButton = YES;
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                              [UIColor blueColor],
                                                                                              NSForegroundColorAttributeName,
                                                                                              nil]
                                                                                    forState:UIControlStateNormal];

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
self.searchBar.showsCancelButton = NO;
[self.searchBar resignFirstResponder];
}



回答2:


You can create a view with a UISearchBar at the top and then a UITableView (initially hidden) and add that to your existing view. Hiding the Navigation bar will given the same appearance as UISearchController. You can then show the table view in the search bar delegates when the user starts searching.



来源:https://stackoverflow.com/questions/27327346/uisearchbar-with-hidden-tableview-on-navigationbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!