解決方案對於非半透明導航欄(更少的代碼,更少的普遍性)
你看見白色的毛刺是的tableview的背景色,其通過導航欄和搜索欄之間的差距是明顯的。這個差距絕對是蘋果開發者的疏忽。
因此,解決辦法是這樣的:
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
UIView *topTableViewBG = [[UIView alloc] initWithFrame:CGRectMake(0, -64, CGRectGetWidth(self.tableView.bounds), 64)];
topTableViewBG.backgroundColor = self.navigationController.navigationBar.backgroundColor;
topTableViewBG.tag = 1234567;
[self.tableView insertSubview:topTableViewBG belowSubview:self.tableView.tableHeaderView];
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[[self.tableView viewWithTag:1234567] removeFromSuperview];
}
這裏我添加了一個自定義視圖右側下的搜索欄。它發生在正式的VC轉換之前。該視圖位於特殊點,因此它覆蓋了導航欄和搜索欄之間的差距。 轉換完成後,我刪除了自定義視圖。
UPDATE:通用溶液(更多的代碼,更普遍性)
在溶液上方是好的僅當有不透光的Navbar。對於半透明的導航欄,有一個挑戰是爲我們的'間隙擋板'視圖找到正確的顏色。但儘快我們可以自由地更改搜索欄顏色,我們可以使用搜索欄顏色來實現間隙限制。
讓我們做一些改變我們的代碼
首先,我們需要不透光的搜索欄,所以設置背景圖片搜索欄:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[searchBar setBackgroundImage:[UIImage pixelImageWithColor:SEARCHBAR_GRAY_COLOR] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;
這裏是UIImage的類中的方法,這是上面使用:
+ (UIImage *)pixelImageWithColor:(UIColor *)color {
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate (NULL, 1, 1, 8, 0, cs, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
CGColorSpaceRelease (cs);
CGContextSetFillColorWithColor (ctx, color.CGColor);
CGContextFillRect (ctx, CGRectMake (0.0f, 0.0f, 1.0f, 1.0f));
CGImageRef cgImage = CGBitmapContextCreateImage (ctx);
CGContextRelease (ctx);
UIImage *result = [UIImage imageWithCGImage:cgImage];
CGImageRelease (cgImage);
return result;
}
然後改變我們searchDisplayControllerWillEndSearch
方法:
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
UIView *topTableViewBG = [[UIView alloc] initWithFrame:CGRectMake(0, -64, CGRectGetWidth(self.tableView.bounds), 64)];
topTableViewBG.backgroundColor = SEARCHBAR_GRAY_COLOR;
topTableViewBG.tag = 1234567;
[self.tableView insertSubview:topTableViewBG belowSubview:self.tableView.tableHeaderView];
}
終於searchDisplayControllerDidEndSearch
方法保持不變:
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[[self.tableView viewWithTag:1234567] removeFromSuperview];
}
老實說這種解決方案更具有普遍性和它看起來比一個我在回答第一部分描述的更漂亮。
它也發生在一個實際的設備? – Mario
因爲這種問題,我不在代碼中使用UISearchDisplayController,以及在Popover上顯示結果時可自定義性差。看看這篇博文。它可以幫助你解決這個問題:http://petersteinberger.com/blog/2013/fixing-uisearchdisplaycontroller-on-ios-7/ – Cezar
@Mario是的,它發生在設備上。 – Rick