【问题标题】:How to align vertically UISearchBar and right bar button items如何垂直对齐 UISearchBar 和右栏按钮项
【发布时间】:2017-09-25 15:56:35
【问题描述】:

我正在开发 iOS 应用程序。它有搜索栏和右栏按钮项(几个按钮)。

东西初始化如下:

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;

在功能上,它按预期工作,但看起来有点奇怪:按钮被绘制在搜索栏上方一点:

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

附: 看来,如果我在 cancelButton.frame = CGRectMake(0., y, 30., 30.); 中更改 y 坐标 - 将不起作用。

【问题讨论】:

    标签: ios objective-c uisearchbar


    【解决方案1】:

    尝试在 viewDidAppear 中添加代码,如下所示,

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    
        // Enter your code
    
    }
    

    您将使导航项居中,如果仍然没有更新框架,请尝试,

    在 viewDidAppear 中更新其“y”位置,否则尝试如下设置框架与搜索栏完全相邻,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多