百度搜索了下titleview居中, 没找到满意答案, 研究了一下。发现使用坐标系转化可以很完美的实现titleview的居中。
直接上代码吧
UIView *title_ve = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
title_ve.backgroundColor = [UIColor redColor];
//设置titleview,不过这个view并不是我们需要的居中的view;
self.navigationItem.titleView = title_ve;
__weak typeof(self) weakSelf = self;
//主线程列队一个block, 这样做 可以获取到autolayout布局后的frame,也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
dispatch_async(dispatch_get_main_queue(), ^{
//要居中view的宽度
CGFloat width = 120;
//实际居中的view
UIView *center_ve = [[UIView alloc]init];
center_ve.backgroundColor = [UIColor greenColor];
//设置一个基于window居中的坐标
center_ve.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-width)/2, 20, width, 44);
//坐标系转换到titleview
center_ve.frame = [weakSelf.view.window convertRect:center_ve.frame toView:weakSelf.navigationItem.titleView];
//centerview添加到titleview
[weakSelf.navigationItem.titleView addSubview:center_ve];
});
效果:红色的为titleview,绿色的为居中的view
不管我们是这样
还是这样
或者是这样
绿色的view都是居中的