我們都知道UIScrollView有一種很流暢的切換效果,結合UIPageControl的輔助展示效果,就可以完成一個很不錯的產品介紹功能頁面。下面給大家分享iOS UIScrollView滾動視圖/無限循環滾動/自動滾動功能,具體代碼如下所示;
<UIScrollViewDelegate>#define WIDTH [[UIScreen mainScreen] bounds].size.width#define HEIGHT [[UIScreen mainScreen] bounds].size.height@property (nonatomic, strong)NSTimer *timer; //定時器@property (nonatomic, retain)NSMutableArray *arr; //放圖片的數組@property (nonatomic, retain)UIView *headerView; //tableView的表頭@property (nonatomic, retain)UIImageView *image; //圖片@property (nonatomic, retain)UIScrollView *scrollView; @property (nonatomic, retain)UIPageControl *pageC; //頁碼//設置頭視圖- (void)headImage{ //圖片數組 self.arr = [NSMutableArray arrayWithObjects:@"8.jpg",@"1.jpg", @"2.jpg", @"3.jpg", @"4.jpg", @"5.jpg", @"6.jpg", @"7.jpg", @"8.jpg", @"1.jpg", nil]; self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200 * HEIGHT/667)]; self.scrollView.backgroundColor = [UIColor clearColor]; //設置滾動量 self.scrollView.contentSize = CGSizeMake(WIDTH * self.arr.count, 0); //設置偏移量 self.scrollView.contentOffset = CGPointMake(WIDTH, 0); //設置按頁滾動 self.scrollView.pagingEnabled = YES; //設置是否顯示水平滑動條 self.scrollView.showsHorizontalScrollIndicator = NO; //設置是否邊界反彈 self.scrollView.bounces = NO; //把scrollView添加到tableView的表頭的視圖上 [self.headerView addSubview:self.scrollView]; [_scrollView release]; //循環圖片添加到UIImageView上 for (int i = 0 ; i < self.arr.count; i++) { NSString *name = [self.arr objectAtIndex:i]; UIImage *img = [UIImage imageNamed:name]; self.image = [[UIImageView alloc]init]; self.image.frame = CGRectMake(i * WIDTH, 0, WIDTH, 200 * HEIGHT/667); self.image.image = img; [self.scrollView addSubview:self.image]; [_image release]; } self.scrollView.delegate = self; //設置頁面 self.pageC = [[UIPageControl alloc]initWithFrame:CGRectMake(100 * WIDTH/375, 120 * HEIGHT/667, 200* WIDTH/375, 60*HEIGHT/667)]; self.pageC.backgroundColor = [UIColor clearColor]; //把頁碼添加到頭視圖上 [self.headerView addSubview:self.pageC]; //設置頁碼數 self.pageC.numberOfPages = self.arr.count; //設置選中頁碼的顏色 self.pageC.currentPageIndicatorTintColor = [UIColor brownColor]; //設置未選中的頁碼顏色 self.pageC.pageIndicatorTintColor = [UIColor grayColor]; //設置當前選中頁 self.pageC.currentPage = 0; //核心方法 [self.pageC addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged]; [_pageC release]; //自定義一個定時器方法 [self addTimer];} //定時器執行方法- (void)change:(NSTimer *)time{ if (self.pageC.currentPage == self.pageC.numberOfPages - 1) { self.pageC.currentPage = 0; } else if (self.pageC.currentPage < self.pageC.numberOfPages - 1) { self.pageC.currentPage++; } [self.scrollView setContentOffset:CGPointMake((self.pageC.currentPage + 1) * WIDTH, 0) animated:NO]; }
以上所述是小編給大家介紹的iOS UIScrollView滾動視圖/無限循環滾動/自動滾動的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答