Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

iOS 開發筆記:UIScrollView 與 UIPageControl 的搭配實戰

編輯:關於 Android 程式設計

UIScrollView 是 iOS 裡最基礎的內容滾動視圖。作為父視圖時,它可以承載任意多個子視圖,再透過它特有的 contentSize 屬性來決定可滾動的範圍——水平方向看寬度,垂直方向看高度,設多少就能滾多遠。

UIPageControl 則是頁碼指示器,通常與 scrollView 搭配使用,用來顯示目前頁碼與總頁數。兩者一組,就能做出常見的輪播/分頁效果。

一、水平滾動的 UIScrollView

// 水平方向滾動的 scrollView
UIScrollView *scrollview001 = [[UIScrollView alloc] init];
[self.view addSubview:scrollview001];
scrollview001.backgroundColor = [UIColor redColor];
scrollview001.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(self.view.bounds), 200.0);

// 添加子視圖控件
NSInteger count001 = 10;
CGFloat originX = 0.0;
for (NSInteger index = 0; index < count001; index++) {
    NSString *text = [NSString stringWithFormat:@"第%@個 label", @(index + 1)];
    UILabel *label = [[UILabel alloc] init];
    [scrollview001 addSubview:label];
    label.frame = CGRectMake(originX, 0.0,
                             CGRectGetWidth(scrollview001.bounds),
                             CGRectGetHeight(scrollview001.bounds));
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor colorWithWhite:(random() % 255)
                                              alpha:((random() % 10) / 10)];
    originX += CGRectGetWidth(label.bounds);
}

// 關鍵屬性:控制內容大小,設定後即可滾動
scrollview001.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds) * count001, 200.0);
scrollview001.pagingEnabled = YES;                  // 整頁顯示效果,預設 NO
scrollview001.showsHorizontalScrollIndicator = NO;  // 隱藏水平滾動條
scrollview001.scrollEnabled = YES;                  // 允許手勢滾動
scrollview001.tag = 1000;                           // 用 tag 區分不同 scrollView
[scrollview001 setContentOffset:CGPointMake(320.0, 0.0) animated:YES];  // 跳到第二頁
scrollview001.delegate = self;

幾個屬性值得留意:

  • contentSize:滾動範圍的總尺寸。水平滾動只需設定寬度,垂直滾動只需設定高度。
  • pagingEnabled:設為 YES 後會有「整頁吸附」的效果,預設是 NO。
  • showsHorizontalScrollIndicator/showsVerticalScrollIndicator:是否顯示滾動條,預設顯示。
  • setContentOffset:animated::程式化跳到指定位置,做輪播時經常用到。

二、垂直滾動的 UIScrollView

UIScrollView *scrollview002 = [[UIScrollView alloc]
        initWithFrame:CGRectMake(0.0, 210.0, CGRectGetWidth(self.view.bounds), 200.0)];
[self.view addSubview:scrollview002];

NSInteger count002 = 10;
CGFloat originY = 0.0;
for (NSInteger index = 0; index < count002; index++) {
    NSString *text = [NSString stringWithFormat:@"第%@個 label", @(index + 1)];
    UILabel *label = [[UILabel alloc] init];
    [scrollview002 addSubview:label];
    label.frame = CGRectMake(0.0, originY,
                             CGRectGetWidth(scrollview002.bounds),
                             CGRectGetHeight(scrollview002.bounds));
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.3];
    originY += CGRectGetHeight(label.bounds);
}

scrollview002.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds),
                                       CGRectGetHeight(scrollview002.bounds) * count002);
scrollview002.pagingEnabled = YES;
scrollview002.tag = 2000;
scrollview002.delegate = self;

與水平版本唯一不同之處,在於子視圖沿 Y 軸堆疊,contentSize 改為累加高度。

三、加上 UIPageControl

UIPageControl *pagecontroll = [[UIPageControl alloc] init];
[self.view addSubview:pagecontroll];
pagecontroll.backgroundColor = [UIColor clearColor];
pagecontroll.frame = CGRectMake(((CGRectGetWidth(self.view.bounds) - 200.0) / 2),
                                (200.0 - 20.0 - 10.0), 200.0, 20.0);

pagecontroll.numberOfPages = count001;              // 總頁數
pagecontroll.currentPage = 1;                       // 目前頁,從 0 起算
pagecontroll.currentPageIndicatorTintColor = [UIColor greenColor];  // 目前頁小圓點顏色
pagecontroll.pageIndicatorTintColor = [UIColor whiteColor];         // 其餘小圓點顏色
pagecontroll.tag = 3000;

四、委派方法:讓頁碼跟著滾動走

使用委派前別忘了三步:設定 delegate、宣告遵守 UIScrollViewDelegate 協議、實作委派方法。

@interface ViewController () <UIScrollViewDelegate>
@end

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger tag = scrollView.tag;
    if (1000 == tag) {
        // 水平方向:用位移量除以頁寬算出目前頁
        CGFloat offsetX = scrollView.contentOffset.x;
        NSInteger page = offsetX / CGRectGetWidth(self.view.bounds);
        NSLog(@"offsetX=%@, 第%@頁", @(offsetX), @(page + 1));

        UIPageControl *pagecontroll = (UIPageControl *)[self.view viewWithTag:3000];
        pagecontroll.currentPage = page;

        // 無限循環:滑到尾端就跳回第一頁
        CGFloat offsetChange = CGRectGetWidth(self.view.bounds) * (10 - 1) + 40.0;
        if (offsetX >= offsetChange) {
            [scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:NO];
            pagecontroll.currentPage = 0;
        } else if (offsetX <= -40.0) {
            [scrollView setContentOffset:
                CGPointMake(CGRectGetWidth(self.view.bounds) * (10 - 1), 0.0) animated:NO];
            pagecontroll.currentPage = 9;
        }
    } else if (2000 == tag) {
        // 垂直方向:用位移量除以頁高算出目前頁
        CGFloat offsetY = scrollView.contentOffset.y;
        NSInteger page = offsetY / CGRectGetHeight(scrollView.bounds);
        NSLog(@"offsetY=%@, 第%@頁", @(offsetY), @(page + 1));
    }
}

無限循環的小技巧是留一點「緩衝區」(這裡是 40pt):當位移超出尾端閾值就無痛跳回首頁,反向滑動超出臨界值則跳回末頁,使用者幾乎察覺不到接縫。

五、其他常用的滾動委派方法

// 即將開始拖動
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"即將開始拖動");
}

// 手指抬起、即將結束拖動(可透過 targetContentOffset 調整最終停點)
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
                targetContentOffset:(inout CGPoint *)targetContentOffset {
    NSLog(@"即將結束拖動");
}

// 結束拖動,decelerate 表示之後是否還會繼續滑行
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate {
    NSLog(@"結束拖動");
}

// 即將進入減速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    NSLog(@"拖動即將釋放");
}

// 完全停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"拖動已經釋放");
    // 這裡通常是最適合同步頁碼的時機
}

// 由 setContentOffset/scrollRectVisible:animated: 觸發的動畫結束(非動畫則不呼叫)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { }

// 縮放相關
- (void)scrollViewDidZoom:(UIScrollView *)scrollView { }

- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;   // 回傳 nil 則不進行縮放
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view { }

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
                       withView:(nullable UIView *)view
                         atScale:(CGFloat)scale { }

// 是否允許點擊狀態列回到頂部,未實作時預設 YES
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    return YES;
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView { }

實務上有個選擇建議:同步頁碼放在 scrollViewDidScroll: 可以即時跟手,但呼叫頻率很高;放在 scrollViewDidEndDecelerating: 則較省資源,卻會在靜止後才更新。若追求流暢的視覺回饋,通常兩處都寫,前者負責即時更新、後者負責收尾校正。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved