iOS UIScrollView的基本使用

黑暗森林的歌者發表於2018-02-26
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    scrollView.backgroundColor = [UIColor redColor];
    // 是否支援滑動最頂端
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;
    // 設定內容大小
    scrollView.contentSize = CGSizeMake(320, 460*10);
    // 是否反彈
    scrollView.bounces = NO;
    // 是否分頁
    scrollView.pagingEnabled = YES;
    // 是否滾動
    scrollView.scrollEnabled = NO;
    //是否顯示滾動條
    scrollView.showsHorizontalScrollIndicator = NO;
    // 設定indicator風格
    scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    // 設定內容的邊緣和Indicators邊緣
    scrollView.contentInset = UIEdgeInsetsMake(0, 50, 50, 0);
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 50, 0, 0);
    // 提示使用者,Indicators flash
    [scrollView flashScrollIndicators];
    // 是否同時運動,lock
    scrollView.directionalLockEnabled = YES;
複製程式碼
// 返回一個放大或者縮小的檢視
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
     
}
// 開始放大或者縮小
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:
(UIView *)view {
     
}
 
// 縮放結束時
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale  {
     
}
  
// 檢視已經放大或縮小
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    NSLog(@"scrollViewDidScrollToTop");
}
 
// 是否支援滑動至頂部
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView  {
    return YES;
}
 
// 滑動到頂部時呼叫該方法
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    NSLog(@"scrollViewDidScrollToTop");
}
 
// scrollView 已經滑動
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"scrollViewDidScroll");
}
 
// scrollView 開始拖動
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"scrollViewWillBeginDragging");
}
 
// scrollView 結束拖動
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"scrollViewDidEndDragging");
}
 
// scrollView 開始減速(以下兩個方法注意與以上兩個方法加以區別)
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    NSLog(@"scrollViewWillBeginDecelerating");
}
 
// scrollview 減速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   NSLog(@"scrollViewDidEndDecelerating"); 
}
複製程式碼

有時候需要做出翻頁效果,使用代理方法得到現在所在的頁面數

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
   CGPoint offset = scrollView.contentOffset; CGFloat currentPage = offset.x / (self.view.bounds.size.width); 
//計算當前的頁碼 
}
複製程式碼

或者使scrllView滾動到指定頁

//在停止拖動的時候計算偏移量

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
      //計算當前的頁碼
     CGPoint offset = scrollView.contentOffset;
        pageController.currentPage = offset.x / (self.view.bounds.size.width); 
        //設定scrollview的顯示為當前滑動到的頁面      
        [scrollView setContentOffset:CGPointMake(self.view.bounds.size.width * (pageController.currentPage),               scroll.contentOffset.y) animated:YES];         
}
複製程式碼

相關文章