1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 //滚动视图,可以对屏幕内容进行滚屏查看。 4 5 _scrollView = [[UIScrollView alloc]init]; 6 7 _scrollView.frame = CGRectMake(10, 50, 300, 400); 8 9 _scrollView.bounces = YES; 10 11 //是否允许通过点击屏幕让滚动视图响应事件 12 _scrollView.userInteractionEnabled = YES; 13 14 //设置画布大小,纵向效果 15 _scrollView.contentSize = CGSizeMake(300, 400*3); 16 17 18 for(int i=0 ;i<3;i++) 19 { 20 //生成图片名称 21 NSString* strName = [NSString stringWithFormat:@"%d.jpg",i+1]; 22 23 UIImage* image = [UIImage imageNamed:strName]; 24 25 //创建视图对象 26 UIImageView* iView = [[UIImageView alloc]init]; 27 //图像赋值 28 iView.image = image; 29 //设置图像试图在滚动视图画布中的位置 30 iView.frame = CGRectMake(0, 400*i, 300, 400); 31 32 [_scrollView addSubview:iView]; 33 34 } 35 36 [self.view addSubview:_scrollView]; 37 38 //取消按页滚动效果 39 _scrollView.pagingEnabled = NO; 40 41 //滚动视图画布的移动位置,偏移位置 42 _scrollView.contentOffset = CGPointMake(0, 0); 43 //将当前视图控制器作为代理对象 44 _scrollView.delegate = self; 45 46 } 47 48 -(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 49 { 50 // _scrollView.contentOffset = CGPointMake(0, 0); 51 52 //带有动画效果的,移动到指定位置 53 54 [_scrollView scrollRectToVisible:CGRectMake(0, 600, 300, 400) animated:YES]; 55 56 } 57 58 59 //可以使用此函数,监控滚动视图的位置 60 -(void) scrollViewDidScroll:(UIScrollView *)scrollView 61 { 62 NSLog(@"y = %f",scrollView.contentOffset.y); 63 } 64 65 //由此,我在这里总结一共几个事件 66 //拖动:即将开始拖动,即将结束拖动,已经结束拖动。后两者是连贯的 67 //减速:即将开始减速,已经结束减速 68 -(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate 69 { 70 NSLog(@"已经结束拖动"); 71 } 72 73 -(void) scrollViewWillBeginDragging:(UIScrollView *)scrollView 74 { 75 NSLog(@"即将开始拖动"); 76 } 77 78 -(void) scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset 79 { 80 NSLog(@"即将结束拖动"); 81 } 82 83 -(void) scrollViewWillBeginDecelerating:(UIScrollView *)scrollView 84 { 85 NSLog(@"视图即将开始减速"); 86 } 87 88 //视图停止时调用 89 -(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView 90 { 91 NSLog(@"视图已经结束减速"); 92 }
1 @interface ViewController : UIViewController<UIScrollViewDelegate> 2 { 3 //当前视图控制器要实现的协议函数 4 //定义一个滚动视图成员变量 5 UIScrollView* _scrollView; 6 7 8 }