我拿了一个UITableViewController并尝试在其中添加UISearchDisplayController。我从互联网上读了很多代码,但不知道我有什么问题。
我的问题是为什么UISearchDisplayController不要总是坚持在UITableView之上。
这是我的代码
SearchView_controller.h
@interface SearchView_controller : UITableViewController<UISearchBarDelegate,UISearchDisplayDelegate>
@end
SearchView_controller.m
@interface SearchView_controller ()
{
UISearchDisplayController *searchController;
}
@end
@implementation SearchView_controller
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"Test";
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y, self.tableView.frame.size.width, 44)];
[searchBar sizeToFit];
[searchBar setDelegate:self];
searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar
contentsController:self];
[searchController setSearchResultsDataSource:self];
[searchController setSearchResultsDelegate:self];
[searchController setDelegate:self];
[self.tableView setTableHeaderView:searchController.searchBar];
}
-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
UISearchBar *searchBar = searchController.searchBar;
CGRect rect = searchBar.frame;
rect.origin.y = MAX(0, scrollView.contentOffset.y);
searchBar.frame = rect;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"searchview_customecell";
searchview_customecell *cell = (searchview_customecell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.lbl_name.text=@"test";
return cell;
}
searchview_customecell.h
@interface searchview_customecell : UITableViewCell
@property(nonatomic, weak) IBOutlet UILabel *lbl_name;
@end
searchview_customecell.m
@implementation searchview_customecell
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
答案 0 :(得分:2)
最好处理UIViewController
而不是UITableviewController
处理此类内容。
与UITableViewController
一样,视图为tableView
,因此只要添加searchBar
,就会在tableView
上添加。{/ p>
此问题有两种可能的解决方案:
将Tableviewcontroller替换为UIViewController并将搜索栏放在视图的开头(不要将其添加到tableview标题中),然后将其放在tableview中。