相信很多朋友都在使用UISearchController
總會(huì)遇到一些莫名其妙的問(wèn)題串远,當(dāng)然我也遇到了誓斥,下面就記錄下使用UISearchController
中遇到問(wèn)題部分問(wèn)題顾孽。
初始代碼:
UITableViewController *searchResultsController = [[UITableViewController alloc]init];
searchResultsController.tableView.delegate = self;
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.estimatedRowHeight = 80;
searchResultsController.tableView.rowHeight = UITableViewAutomaticDimension;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.95];
self.searchController.searchResultsUpdater = self;
UISearchBar *bar = self.searchController.searchBar;
bar.barTintColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1.0];
bar.tintColor = [UIColor blackColor];
bar.showsBookmarkButton = YES;
bar.translucent = YES;
UIImageView *view = [[[bar.subviews objectAtIndex:0] subviews] firstObject];
view.layer.borderColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1.0].CGColor;
view.layer.borderWidth = 1;
self.tableView.tableHeaderView = bar;
問(wèn)題1:點(diǎn)擊搜索框時(shí)searchResultsController和searchBar間隔44pt久信,并且點(diǎn)擊跳轉(zhuǎn)無(wú)響應(yīng)豁翎,如下圖:
問(wèn)題1.gif
解決辦法,添加代碼:
self.definesPresentationContext = YES;
效果如下:
問(wèn)題1解決方法.gif
問(wèn)題2:在設(shè)置導(dǎo)航欄為不透明時(shí)仅仆,點(diǎn)擊搜索時(shí)searchBar偏移出屏幕
解決辦法同上
問(wèn)題3:在設(shè)置導(dǎo)航欄為不透明時(shí)器赞,點(diǎn)擊搜索框出現(xiàn)如下情況:
問(wèn)題3.gif
解決辦法,添加代碼:
self.extendedLayoutIncludesOpaqueBars = YES;
效果如下:
問(wèn)題3解決辦法.gif
屬性介紹:
// 導(dǎo)航欄是否為半透明
self.navigationController.navigationBar.translucent = YES;
// 如果在當(dāng)前控制器中該屬性為YES時(shí)墓拜,則將設(shè)置新的視圖控制器港柜。如果當(dāng)前控制器中該屬性為NO,則控制器為跟視圖控制
self.definesPresentationContext = NO;
// 是否隱藏navigationBar
self.searchController.hidesNavigationBarDuringPresentation = YES;
// 延伸視圖包是否含不透明的bar
self.extendedLayoutIncludesOpaqueBars = NO;
引起問(wèn)題的原因:
- 出現(xiàn)searchResultsController和searchBar間隔44pt的原因就在于咳榜,UISearchController有個(gè)
hidesNavigationBarDuringPresentation
屬性夏醉,其默認(rèn)值為YES,就是在點(diǎn)擊searchBar時(shí)進(jìn)行搜索時(shí)會(huì)將導(dǎo)航欄隱藏涌韩,并將searchBar移動(dòng)到navigationBar的位置處畔柔,而tableView并不知道searchBar已經(jīng)移動(dòng)到navigationBar的位置所以就多出了44pt; - 在searchResultsController中點(diǎn)擊cell無(wú)法跳轉(zhuǎn)是因?yàn)閟earchResultsController并不是主視圖臣樱,而在設(shè)置
self.definesPresentationContext = YES
后靶擦,系統(tǒng)會(huì)將searchResultsController設(shè)置為新的主視圖; - 在設(shè)置導(dǎo)航欄為不透明時(shí)(
self.navigationController.navigationBar.translucent = NO
)雇毫,點(diǎn)擊搜索時(shí)searchBar偏移出屏幕玄捕,導(dǎo)航欄不透明時(shí),self.view的原點(diǎn)是從導(dǎo)航欄的底部棚放,那么相對(duì)self.view而言navigationBar的x=-64枚粘,所以搜searchBar彈出時(shí)獲取self.navigationController.navigationBar.x = searchBar.x;
,此navigationBar已經(jīng)隱藏,searchBar.x = -64這個(gè)時(shí)候就會(huì)偏移出屏幕飘蚯。 - 那么到searchBar向下偏移64pt原理同上馍迄。
總結(jié):
可能有些地方解釋的不到位,歡迎大家指正局骤。