如何在 UINavigationItem 的右侧显示 UISearchBar?

发布于 2024-10-14 15:57:10 字数 461 浏览 3 评论 0原文

我试图显示 UISearchBar 来代替 UINavigationItem 右侧显示的按钮。我正在使用这段代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    UIBarButtonItem *navRight = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
    [[self navigationItem] setRightBarButtonItem:navRight];

    [searchBar release];
    [navRight release];
}

但是,显示的搜索栏只有几个像素宽。我需要把它弄得更宽。

我是否以错误的方式处理这个问题?这有可能吗?

I am trying to display a UISearchBar in place of the button shown on the right side of the UINavigationItem. I am using this code:

- (void)viewDidLoad {
    [super viewDidLoad];
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    UIBarButtonItem *navRight = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
    [[self navigationItem] setRightBarButtonItem:navRight];

    [searchBar release];
    [navRight release];
}

However, the displayed search bar is only a few pixels wide. I need to make it wider.

Am I going about this the wrong way? Is it at all possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗喜 2024-10-21 15:57:10

您需要在某个时刻设置 UISearchBar 的框架。

ex

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];

编辑:关于UISearchBar下的按钮式工件

您在UISearchBar下看到的按钮y实际上是一个背景元素UISearchBar,而不是搜索栏与 UIBarButtonItem 重叠的结果。由于似乎没有一个很好的方法来隐藏这一点(我希望有人能过来纠正我),我只能向您指出 hack 伴随着 SDK 版本依赖、不优雅的常见危险,并可能带来更多令人头痛的问题。

编辑2:另一个潜在的解决方案

您还可以将UISearchBar的框架高度设置为44(导航栏的高度),然后背景应该与导航栏很好地融合。基于这个< /a> 我最近看到的帖子。

You need to set the UISearchBar's frame at some point.

e.x.

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];

EDIT: Regarding the button-esque artifact under the UISearchBar

The button-y thing that you see under the UISearchBar is actually a background element of the UISearchBar, not the result of the search bar overlapping a UIBarButtonItem. Since there doesn't seem to be a nice way to hide this (and I hope someone can come along and correct me), I can only point you in the direction of a hack that comes with the usual perils of SDK version dependence, inelegance, and potential for more headaches.

EDIT 2: Another potential solution

You could also set your UISearchBar's frame's height to 44 (the height of the navbar) and then the background should blend nicely with the navbar. Based off this SO post I recently saw.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文