滾動視圖UIScrollView高級,協議。
#import@interface ViewController : UIViewController {//協議函數 //定義一個滾動視圖成員變量 UIScrollView * _scrollView; } @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //創建滾動視圖 _scrollView =[[UIScrollView alloc]init]; //設定滾動視圖的位置 _scrollView.frame=CGRectMake(10, 50, 300, 400); //取消彈動效果 _scrollView.bounces=NO; //是否允許通過點擊屏幕讓滾動視圖響應事件 //YES:滾動視圖可以接受觸碰事件 //NO:不接受觸碰事件 // _scrollView.userInteractionEnabled=NO; _scrollView.userInteractionEnabled=YES; //設置畫布的大小,縱向效果 _scrollView.contentSize=CGSizeMake(300, 400*9); for(int i=0;i<10;i++){ //生成圖片名稱 NSString* strName =[NSString stringWithFormat:@"17_%d.png",i+1]; UIImage *image = [UIImage imageNamed:strName]; //創建圖像視圖對象 UIImageView * iView = [[UIImageView alloc]init]; //圖像賦值 iView.image=image; //設置圖像視圖在滾動視圖畫布中的位置 iView.frame=CGRectMake(0, 400*i, 300, 400); [_scrollView addSubview:iView]; } [self.view addSubview:_scrollView]; //取消按頁滾動效果 _scrollView.pagingEnabled=NO; // _scrollView.pagingEnabled=YES; //滾動視圖畫布的移動位置,偏移位置 //功能:決定畫布顯示的最終圖像結果 _scrollView.contentOffset=CGPointMake(0,0); //當前視圖控制器作為代理對象 _scrollView.delegate=self; } -(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{ // _scrollView.contentOffset=CGPointMake(0, 0);//點擊空白處,直接跳到設定的坐標位置 //讓滾動視圖移動到指定位置,動畫移動 [_scrollView scrollRectToVisible:CGRectMake(0, 0, 300, 400) animated:YES]; } //當滾動視圖移動時,只要offset坐標發生變化,都會調用此函數 //參數:調用此協議的滾動視圖對象 //可以使用此函數來監控滾動視圖的位置 - (void) scrollViewDidScroll:(UIScrollView *)scrollView{ NSLog(@"Y=%f",scrollView.contentOffset.y); } //當滾動視圖結束拖動時調用此函數 - (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ NSLog(@"Did End Drag"); } //滾動視圖即將開始被拖動時 -(void) scrollViewWillBeginDragging:(UIScrollView *)scrollView{ NSLog(@"WillBeginDrag"); } //視圖即將結束拖動時調用 -(void) scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{ NSLog(@"Will End Drag"); } //視圖即將減速時調用 -(void) scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{ NSLog(@"Will Begin Decelerating"); } //視圖已經結束減速時調用,視圖停止的瞬間調用 -(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ NSLog(@"視圖停止移動"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end