2017-09-25 23 views
0

我正在iOS应用程序上工作。它有搜索栏和右栏按钮项目(几个按钮)。如何垂直对齐UISearchBar和右键栏按钮项

的东西被初始化如下:

UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; 
UISearchBar *searchBar = searchController.searchBar; 
[searchBar sizeToFit]; 
searchBar.placeholder = @"Search"; 

UIButton *routeButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[routeButton setBackgroundImage:[UIImage imageNamed:@"go_route"] forState:UIControlStateNormal]; 
routeButton.frame = CGRectMake(0., 0., 30., 30.); 

UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[cancelButton setBackgroundImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal]; 
cancelButton.frame = CGRectMake(0., 0., 30., 30.); 

UIBarButtonItem *routeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:routeButton]; 
UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton]; 

self.navigationItem.rightBarButtonItems = @[cancelButtonItem, routeButtonItem]; 
self.navigationItem.titleView = searchBar; 

功能上,它工作正常,但看起来有点怪:按钮绘制的位上比搜索栏:

enter image description here

我想让按钮稍微低一些,与搜索栏垂直对齐。我如何实现它?

P.S. 看来,如果我改变y坐标cancelButton.frame = CGRectMake(0., y, 30., 30.); - 它没有任何效果。

回答

0

尝试增加你的代码在viewDidAppear如下,

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 

    // Enter your code 

} 

您将获得导航项目为中心,如果仍然没有更新框架的尝试,

更新在viewDidAppear其“Y”的位置,否则试试如下设置帧恰好毗邻搜索栏,

routeButton.center = CGPointMake(routeButton.center.x, searchBar.center.y); 
+0

先后此解决方案为您的情况? – Bharath