IOS ——UI篇—— UISegmentedControl与UIScrollView的结合
这种结合方式和 UIPageControl的结合方式相同,下面做简单的示例:
1 #import "ViewController.h" 2 3 @interface ViewController ()<UIScrollViewDelegate> 4 { 5 UISegmentedControl *segment; 6 UIScrollView *scrollView; 7 } 8 @end 9 10 @implementation ViewController 11 12 - (void)viewDidLoad { 13 [super viewDidLoad]; 14 15 scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 30, 300, 400)]; 16 scrollView.backgroundColor = [UIColor whiteColor]; 17 scrollView.contentSize = CGSizeMake(900, 400); 18 scrollView.delegate = self; 19 scrollView.pagingEnabled = YES; 20 scrollView.scrollEnabled = NO;//是否允许滚动(默认允许) 21 [self.view addSubview:scrollView]; 22 23 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)]; 24 view.backgroundColor = [UIColor grayColor]; 25 [scrollView addSubview:view]; 26 27 UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(300, 0, 300, 400)]; 28 view1.backgroundColor = [UIColor brownColor]; 29 [scrollView addSubview:view1]; 30 31 UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(600, 0, 300, 400)]; 32 view2.backgroundColor = [UIColor purpleColor]; 33 [scrollView addSubview:view2]; 34 35 36 segment = [[UISegmentedControl alloc] initWithItems:@[@"1",@"2",@"3"]]; 37 segment.frame = CGRectMake(10, 450,200, 40); 38 segment.selectedSegmentIndex = 0; 39 [segment addTarget:self action:@selector(segmentChange) forControlEvents:UIControlEventValueChanged]; 40 [self.view addSubview:segment]; 41 42 } 43 -(void)segmentChange{ 44 CGPoint p = {segment.selectedSegmentIndex*300,0}; 45 [scrollView setContentOffset:p animated:YES]; 46 } 47 48 //停止减速--scrollview不动了之后调用的方法 49 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ 50 //停止减速--scrollview不动了 51 // NSLog(@"不动了"); 52 53 CGPoint p = scrollView.contentOffset; 54 float w = p.x; 55 56 int index = w/scrollView.frame.size.width; 57 NSLog(@"当前:%d页",index); 58 59 segment.selectedSegmentIndex = index; 60 61 } 62 63 - (void)didReceiveMemoryWarning { 64 [super didReceiveMemoryWarning]; 65 // Dispose of any resources that can be recreated. 66 } 67 68 @end
感谢您的访问!
若对您有帮助或有兴趣请关注博客:http://www.cnblogs.com/Rong-Shengcom/