最近做一个东西,需要在导航栏上居中显示一个UISegmentedControl,查看网上的一些代码,大部分都是采用self.navigationItem.rightBarButtonItem = segButton的形式,但是这样不会居中,又尝试在titleView上add segmentControl,发现也不行,经过研究,发现只要设置navigationBar的titleView就可以了。
效果图如下:
代码如下:
NSArray *segmentedArray = [NSArray arrayWithObjects:"学习卡","活动学习卡",nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
segmentedControl.frame = CGRectMake(0, 0, 100, 30);
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.tintColor = [UIColor colorWithRed:154/255.0 green:224/255.0 blue:192/255.0 alpha:1];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[segmentedControl addTarget:self action:@selector(indexDidChangeForSegmentedControl:)
forControlEvents:UIControlEventValueChanged];
//方法1
//[self.navigationController.navigationBar.topItem setTitleView:segmentedControl];
//方法2
[self.navigationItem setTitleView:segmentedControl];