首页 > 解决方案 > 使用布局锚将自定义导航栏项居中

问题描述

我创建了一个自定义导航项(同时包含 title 和 a UISearchBar)来替换 iOS 上的标准导航标题,并且我正在尝试使用布局锚将其置于 UINavigationBar 的中心。

但是,布局约束[self.navigationItem.titleView.centerXAnchor constraintEqualToAnchor:self.navigationController.navigationBar.centerXAnchor].active = YES;不起作用,UIView包含搜索栏显示在UINavigationBar.

其他约束:

如何使导航栏项居中?

ScreenViewController.m

- (void) viewDidLoad {
    [super viewDidLoad];

    // Create the search bar
    self.searchBar = [SearchBar new];

    // Create a new UIView as titleView (otherwise I'm receiving an error)   
    self.navigationItem.titleView = [UIView new];

    // Add into view hierarchy and turn off auto constraints
    [self.navigationController.navigationBar addSubview:self.navigationItem.titleView];
    [self.navigationItem.titleView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.navigationItem.titleView addSubview:self.searchBar.view];            
    [self.searchBar.view setTranslatesAutoresizingMaskIntoConstraints:NO];

    // Set anchors for the wrapping view
    [self.navigationItem.titleView.widthAnchor constraintEqualToAnchor:self.navigationController.navigationBar.widthAnchor multiplier:1.0/3.0].active = YES;
    //[self.navigationItem.titleView.heightAnchor constraintEqualToConstant:50.0].active = YES;
    [self.navigationItem.titleView.topAnchor constraintEqualToAnchor:self.navigationController.navigationBar.topAnchor].active = YES;
    [self.navigationItem.titleView.centerXAnchor constraintEqualToAnchor:self.navigationController.navigationBar.centerXAnchor].active = YES;
    [self.navigationItem.titleView.bottomAnchor constraintEqualToAnchor:self.navigationController.navigationBar.bottomAnchor].active = YES;

    // Set anchors for the search bar
    [self.searchBar.view.widthAnchor constraintEqualToAnchor:self.navigationItem.titleView.widthAnchor multiplier:1.0].active = YES;
    //[self.navigationItem.titleView.heightAnchor constraintEqualToConstant:50.0].active = YES;
    [self.searchBar.view.topAnchor constraintEqualToAnchor:self.navigationItem.titleView.topAnchor].active = YES;
    [self.searchBar.view.bottomAnchor constraintEqualToAnchor:self.navigationItem.titleView.bottomAnchor].active = YES;
    //[self.searchBar.view.leftAnchor constraintEqualToAnchor:self.navigationItem.titleView.leftAnchor].active = YES;
    //[self.searchBar.view.rightAnchor constraintEqualToAnchor:self.navigationItem.titleView.rightAnchor].active = YES;
    [self.searchBar.view.centerXAnchor constraintEqualToAnchor:self.navigationItem.titleView.centerXAnchor].active = YES;
}

预期结果: 居中搜索栏

我得到的(标题视图不居中): 居中搜索栏问题

查看层次结构:

查看层次结构

标签: iosautolayoutuinavigationbaruisearchbarlayout-anchor

解决方案


你的所作所为既不可能又违法。您根本没有制作“自定义导航栏项目”(如您的标题中所述)。您正在尝试将子视图直接添加到导航栏。你不能那样做。将某些东西放入导航栏的方法是将其分配到视图控制器的navigationItem中,或者作为栏按钮项或作为导航项的真实titleView。(你调用你的变量 titleView,但实际上你并没有把它变成导航项的titleView。)


推荐阅读