標籤:分頁 顯示 效果 開發
分頁相關屬性
只要將UIScrollView的pageEnabled屬性設定為YES,UIScrollView會被分割成多個獨立頁面,裡面的內容就能進行分頁展示一般會配合UIPageControl增強分頁效果,UIPageControl常用屬性如下 一共有多少頁@property(nonatomic) NSInteger numberOfPages;當前顯示的頁碼@property(nonatomic) NSInteger currentPage; 只有一頁時,是否需要隱藏頁碼指標@property(nonatomic) BOOL hidesForSinglePage; 其他頁碼指標的顏色@property(nonatomic,retain) UIColor *pageIndicatorTintColor;當前頁碼指標的顏色@property(nonatomic,retain) UIColor *currentPageIndicatorTintColor;
分頁圖片輪播器執行個體
#define ImageCount 5#import "ViewController.h"@interface ViewController ()<UIScrollViewDelegate>@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;/** * 定時器 */@property(nonatomic,strong)NSTimer* timer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; //0.一些固定的尺寸參數 CGFloat imageW=self.scrollView.frame.size.width; CGFloat imageH=self.scrollView.frame.size.height; CGFloat imageY=0; //1.添加imageCount個圖片到scrollView中 for (int i=0; i<ImageCount; i++) { UIImageView* imageView =[[UIImageView alloc]init]; //設定frame CGFloat imageX=i*imageW; imageView.frame=CGRectMake(imageX, imageY, imageW, imageH); //設定圖片 NSString* name=[NSString stringWithFormat:@"img_0%d",i+1]; imageView.image=[UIImage imageNamed:name]; [self.scrollView addSubview:imageView]; } //2.設定內容尺寸 CGFloat contentW=ImageCount*imageW; self.scrollView.contentSize=CGSizeMake(contentW, 0); //3.隱藏水平捲軸 self.scrollView.showsHorizontalScrollIndicator=NO; //4.分頁 self.scrollView.pagingEnabled=YES; self.scrollView.delegate=self; //5.設定pageControl的總頁數 self.pageControl.numberOfPages=ImageCount; //6.添加定時器(每隔2秒調用一次self的nextImage方法) [self addTimer];}/** * 添加定時器 */- (void)addTimer{ self.timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES]; //迴圈控制多線程 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];}/** * 移除定時器 */- (void)removeTimer{ [self.timer invalidate]; self.timer=nil;}/** * 下一張圖片 */- (void)nextImage{ //1.增加pageControl的頁碼 int page=0; if (self.pageControl.currentPage==ImageCount-1) { page=0; }else{ page=self.pageControl.currentPage+1; } //2.計算scrollView滾動的位置 CGFloat offsetX=page*self.scrollView.frame.size.width; CGPoint offset=CGPointMake(offsetX, 0); [self.scrollView setContentOffset:offset animated:YES];}#pragma mark - 代理方法/** * 當scrollView正在滾動就會調用 */- (void) scrollViewDidScroll:(UIScrollView *)scrollView{ //根據scrollView的滾動位置決定pageControl顯示第幾頁 CGFloat scrollW=scrollView.frame.size.width; int page=(scrollView.contentOffset.x+scrollW*0.5)/scrollW; self.pageControl.currentPage=page;}/** * 開始拖拽的時候調用 */- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{ //停止定時器(一旦定時器停止了,就不能在使用了) [self removeTimer];}/** * 停止拖拽的時候調用 */- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ //開啟定時器 [self addTimer];}@end
Storyboard
iOS開發 - UIPageControl實現分頁圖片輪播器