目标 c 中 UINavigationBar 右侧的 UISearchBar

Posted

技术标签:

【中文标题】目标 c 中 UINavigationBar 右侧的 UISearchBar【英文标题】:UISearchBar in right of UINavigationBar in objective c 【发布时间】:2012-01-18 08:57:32 【问题描述】:

我创建了一个 iPad 应用程序,我希望我的 searchBar 位于导航栏的右侧。

当我在导航栏中添加搜索栏时,它位于导航栏的中间。相反,我想在中间显示一个特定的图像。

我怎样才能做到这一点?

这是我的代码 sn-p,

[self.navigationController.navigationBar setTintColor:[[UIColor alloc]initWithRed:150.0 / 255 green:22.0 / 255 blue:22.0 / 255 alpha:0.0]];

UIImage *image = [UIImage imageNamed:@"logo(1).png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.navigationItem setTitleView:imageView];

self.navigationItem.titleView = sBar;

[titleView release];

使用上面的代码,我只能在模拟器中看到 searchBar(位于中间)。

【问题讨论】:

首先,为什么要发布titleView?也许你需要释放imageView。其次,如果将sBar添加到self.navigationItem.titleView,则只有条形可见。如果你想看到你需要这样做的图像:self.navigationItem.titleView = imageView. 搜索栏可以试试看UIBarButtonItem reference。也许可以传入一个 UIView(如 UISearchBar)并将该按钮作为self.navigationItem.rightBarButtonItem 放在导航栏中 【参考方案1】:

试试这个:

UISearchBar *searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 40)] autorelease];
searchBar.backgroundImage = [[[UIImage alloc] init] autorelease];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:searchBar] autorelease];

您可以随时更改框架。请始终牢记backgroundImage 属性仅在 ios 5 中可用。您应该搜索替代选项以摆脱 iOS 4.x 的背景

让我知道这是否适合你。

【讨论】:

如果你知道怎么做就这么简单!非常感谢。【参考方案2】:

试试:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sBar];

【讨论】:

【参考方案3】:

我搞砸了,我也无法正确对齐(在搜索栏旁边添加了几个按钮之后)。

除非有人提出更好的解决方案,否则您最好将 NavigationBar ([self.navigationController setNavigationBarHidden:YES]) 隐藏在该视图中,并将其替换为具有您需要的所有 UI 元素的 UIView。我认为这种行为更容易预测。

【讨论】:

以上是关于目标 c 中 UINavigationBar 右侧的 UISearchBar的主要内容,如果未能解决你的问题,请参考以下文章