UISearchBar和UINavigationItem

tbe*_*nin 2 iphone uisearchbar uinavigationitem

我似乎无法让UISearchBar从导航栏中的最左侧到最右侧定位.在 - (void)viewDidLoad方法中,我有以下代码:

UISearchBar *sb = [[UISearchBar alloc] initWithFrame:self.tableView.tableHeaderView.frame];
sb.delegate = self;
self.navigationItem.titleView = sb;
[sb sizeToFit];
[sb release];
Run Code Online (Sandbox Code Playgroud)

当你构建和运行时,乍一看它看起来很好.但是,仔细观察,你可以看出左边有一个边距/空格.这在宏观计划中并不是什么大不了的事,但当我点击搜索栏开始搜索时,我会将取消按钮设置为视图.因为搜索栏位于右侧略微位置,所以动画不稳定,取消按钮会像这样掉落: 链接文本

似乎UINavigationItem就像一个有三个单元格的表,在第一个和最后一个上面有一个我无法删除的填充 - 似乎也没有办法将它们"合并"在一起然后放置搜索栏那里.我知道这种外观是可能的,因为AppStore搜索在导航栏中有一个搜索栏,它一直到边缘.任何人都知道如何让搜索栏一直到边缘,所以我的滑入取消按钮动画将正常工作?

Hil*_*ell 5

实际上,有一个非常简单的解决方案.您所要做的就是为后面的项目创建一个零宽度视图:

UIView *hackView = [[UIView alloc] initWithFrame:CGRectZero];
UIBarButtonItem *hackItem = [[UIBarButtonItem alloc] initWithCustomView:hackView];      
self.navigationItem.backBarButtonItem = hackItem;
[hackView release];
[hackItem release];

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[searchBar sizeToFit];
self.navigationItem.titleView = searchBar;
[searchBar release];
Run Code Online (Sandbox Code Playgroud)

一定要在loadView方法中执行此操作,而不是init.我不确定为什么会有所作为,但确实如此.

显然这是关于时间的.在loadView中使用它已停止为我工作,但将它放在viewWillAppear工作(检查,以便它只做一次,当然).我认为这个想法是在一些初始化完成后设置titleView.