在我的导航栏中,我有一个放大镜图标,会显示一个搜索栏。我没有使用UISearchDisplayController,因此我选择构建自己的UINavigationItem,然后使用pushNavigationItem将其推送到标准UINavigationItem。
问题是UINavigationItem似乎被推到右边8个像素左右。这会导致取消按钮(带有本地化文本'Annuleren')非常接近屏幕边缘。
我尝试在运行时检查self.mySearchBar.bounds,但原点是0,0。我玩过AutoLayout并以编程方式添加了约束,但我没有成功。我希望没有AutoLayout就可以。
这是我的代码:
- (IBAction)displaySearchBar:(id)sender {
if (!self.mySearchNavigationItem)
{
self.mySearchNavigationItem = [[UINavigationItem alloc] initWithTitle:@""];
self.mySearchNavigationItem.hidesBackButton = YES;
self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.mySearchBar.showsCancelButton = YES;
self.mySearchBar.delegate = self;
[self.mySearchBar sizeToFit];
[self.mySearchBar setPlaceholder:@"Zoeken..."];
UIView *barWrapper = [[UIView alloc]initWithFrame:self.mySearchBar.bounds];
[barWrapper addSubview:self.mySearchBar];
self.mySearchNavigationItem.leftBarButtonItem = nil;
self.mySearchNavigationItem.backBarButtonItem = nil;
self.mySearchNavigationItem.titleView = barWrapper;
UIButton *cancelButton;
UIView *topView = self.mySearchBar.subviews[0];
for (UIView *subView in topView.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
cancelButton = (UIButton*)subView;
}
}
if (cancelButton) {
[cancelButton setTitle:@"Annuleren" forState:UIControlStateNormal];
}
}
[self.navigationController.navigationBar pushNavigationItem:self.mySearchNavigationItem animated:YES];
NSTimeInterval delay;
if (self.tableView.contentOffset.y >1000) delay = 0.4;
else delay = 0.1;
[self performSelector:@selector(activateSearch) withObject:nil afterDelay:delay];
}
答案 0 :(得分:0)
尝试:
self.navigationController.navigationBar.barTintColor = self.mySearchBar.barTintColor;
如果不起作用,您可以在导航控制器中添加底色视图,这是您想要的颜色。这可能很有用:Get the right color in iOS7 translucent navigation bar
答案 1 :(得分:0)
经过几个小时的搜索,我放弃了,然后进行了肮脏的修复。我会暂时打开它,以防有人知道为什么我的搜索栏向右移动了8个像素。
在显示UINavigationItem之前,我将整个UINavigationBar移动到x坐标-8。
self.navigationController.navigationBar.frame = CGRectMake(-8.0, self.navigationController.navigationBar.frame.origin.y, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
[self.navigationController.navigationBar pushNavigationItem:self.mySearchNavigationItem animated:YES];
然后在取消按钮上单击,我将其移回x坐标0。
- (IBAction)cancelSearchBar:(id)sender {
[self.navigationController.navigationBar popNavigationItemAnimated:YES];
self.navigationController.navigationBar.frame = CGRectMake(0.0, self.navigationController.navigationBar.frame.origin.y, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
}