首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UIScrollView 分頁時改變背景顏色:實作 scrollViewDidScroll 判斷頁碼

     編輯:程式設計綜合問答

實作 UIScrollViewDelegate 的 scrollViewDidScroll:,根據 contentOffset.x 計算當前頁碼,切換背景顏色。

程式碼

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat pageWidth = 360; // 單頁寬度
    NSInteger page = floor(scrollView.contentOffset.x / pageWidth);
    if (page == 1) {
        self.scrollView.backgroundColor = [UIColor greenColor]; // 第 2 頁
    } else {
        self.scrollView.backgroundColor = [UIColor blueColor]; // 第 1 頁
    }
}

設定委派

scrollView.delegate = self;
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(pageWidth * totalPages, scrollView.bounds.size.height);

注意

  • pageWidth 需與實際分頁寬度一致。
  • 若頁面數較多,建議用陣列/字典對應頁碼顏色。
  • 背景色變更會觸發重繪,效能影響極小。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved