目标c中,UINavigationBar右侧的UISearchBar

3
我创建了一个iPad应用程序,我希望我的搜索栏位于导航栏的右侧。
当我将搜索栏添加到导航栏中时,它会被放置在导航栏的中间。而我想要在中间显示特定的图像。
如何实现这一点?
以下是我的代码片段:
[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];

使用上述代码后,我只能在模拟器中看到位于中间的搜索栏。

首先,为什么要释放 titleView?也许你需要释放 imageView。其次,如果你将 sBar 添加到 self.navigationItem.titleView 中,只有该栏是可见的。如果你想看到图像,你需要这样做:self.navigationItem.titleView = imageView - Lorenzo B
对于搜索栏,您可以尝试查看UIBarButtonItem参考文档。也许可以传入一个UIView(例如UISearchBar),并将该按钮放置在导航栏中作为self.navigationItem.rightBarButtonItem - Lorenzo B
3个回答

12

试试这个:

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的背景。

如果这对你有用,请告诉我。


如果你知道怎么做,这很容易!非常感谢。 - virtualnobi

0

我乱搞了一下,加了几个按钮到搜索栏旁边后也没能使它们正确对齐。

除非有更好的解决方案被提出,您最好只隐藏NavigationBar([self.navigationController setNavigationBarHidden:YES]),并用包含所有所需 UI 元素的 UIView 替换它。我认为这种做法行为更加可预测。


0

尝试:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接