前言
- 这篇博客可以结合这篇来看,我是在写同一个界面碰到的问题
实例代码
NSArray *array = @[@"精选文章", @"精选文章", @"全部文章"];
_segmentedControl = [[UISegmentedControl alloc] initWithItems:array];
_segmentedControl.frame = CGRectMake(0, 0, 320, 30);
_segmentedControl.selectedSegmentIndex = 0;
_segmentedControl.tintColor = [UIColor whiteColor];
_segmentedControl.momentary = NO;
[_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:16]}
forState:UIControlStateNormal];
[_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:0.45f green:0.45f blue:0.45f alpha:1.00f], NSFontAttributeName:[UIFont systemFontOfSize:16]}
forState:UIControlStateSelected];
[_segmentedControl setBackgroundColor:[UIColor colorWithRed:0.32f green:0.32f blue:0.32f alpha:1.00f]];
[_segmentedControl setBackgroundImage:[UIImage imageNamed:@"1111"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[_segmentedControl setDividerImage:[UIImage imageNamed:@"essay_line"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[_segmentedControl addTarget:self action:@selector(roll:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_segmentedControl];
- (void) roll: (UISegmentedControl *) sem {
NSInteger selectindext = _segmentedControl.selectedSegmentIndex;
if (selectindext == 0) {
[_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
if (selectindext == 1) {
[_scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
}
if (selectindext == 2) {
[_scrollView setContentOffset:CGPointMake(640, 0) animated:YES];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.x == 0) {
_segmentedControl.selectedSegmentIndex = 0;
} else if (scrollView.contentOffset.x == 320) {
_segmentedControl.selectedSegmentIndex = 1;
} else if (scrollView.contentOffset.x == 640) {
_segmentedControl.selectedSegmentIndex = 2;
}
}
心得
- NSInteger selectindext = _segmentedControl.selectedSegmentIndex;这句话调用select属性,得出此时按下去的是第几个按钮
- 监听scrollview的滑动位置,设定按钮的选择
- 需要加上