想在UIScrollView正在滾動或滾動到某個位置又或者中止滾動時作一些特定的操做,那麼就須要監聽UIScrollView的整個滾動過程,而當UIScrollView發生一系列的滾動操做時,會自動通知它的代理(delegate)對象,給它的代理髮送相應的消息,讓代理得知它的滾動狀況。也就是說,要想監聽UIScrollView的滾動過程,就必須先給UIScrollView設置一個代理對象,而後經過代理得知UIScrollView的滾動過程。atom
看UIScrollView的代碼,會發現她有一個屬性delagatespa
UIScrollView將delegate須要實現的方法都定義在了UIScrollViewDelegate協議中,所以要想成爲UIScrollView的delegate(能夠是任意類型的對象),必須遵照UIScrollViewDelegate協議,而後實現協議中相應的方法,就能夠監聽UIScrollView的滾動過程了。代理
#import "ViewController.h" //在類擴展中遵照協議 @interface ViewController () <UIScrollViewDelegate> @property (weak, nonatomic) IBOutlet UIScrollView *scrollview; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xx"]]; [self.scrollview addSubview:imageView]; self.scrollview.backgroundColor = [UIColor redColor]; self.scrollview.contentSize = imageView.image.size; // 設置代理 self.scrollview.delegate = self; } #pragma mark - <UIScrollViewDelegate> /** * 滑動的時候調用 */ - (void)scrollViewDidScroll:(UIScrollView *)scrollView { NSLog(@"scrollViewDidScroll------"); } /** * 即將開始拖拽的時候調用 */ - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { NSLog(@"scrollViewWillBeginDragging------"); } /** * 結束拖拽的時候調用 */ - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { NSLog(@"scrollViewDidEndDragging------"); } /** * (減速完畢)因爲慣性中止滾動的時候調用 */ - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { NSLog(@"scrollViewDidEndDecelerating------"); } @end
UIScrollView是能夠對她的子控件進行縮放的code
// // ViewController.m // UIScrollView的使用 // // Created by Daniel on 16/3/3. // Copyright © 2016年 Daniel. All rights reserved. // #import "ViewController.h" @interface ViewController () <UIScrollViewDelegate> @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //子控件 UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xx"]]; [self.scrollView addSubview:imageView]; self.imageView = imageView; self.scrollView.backgroundColor = [UIColor orangeColor]; self.scrollView.contentSize = imageView.image.size; //設置代理 self.scrollView.delegate = self; //設置最小的縮放比例 self.scrollView.minimumZoomScale = 0.3; //設置最大的縮放比例 self.scrollView.maximumZoomScale = 1.5; } #pragma mark - <UIScrollViewDelegate> /** 該方法的返回值決定了要縮放的內容,並且被縮放的只能是UIScrollView的子控件 */ - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.imageView; } @end