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
复制代码

 

posted @   #零下一度&  阅读(511)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
点击右上角即可分享
微信分享提示