標籤:.sh height 決定 select uiimage atomic copy 固定 lld
//// ZQRViewController.m// 04-圖片輪播器//// Created by apple on 17-08-24.// Copyright (c) 2017年 zzqqrr. All rights reserved.//#define ZQRImageCount 5#import "ZQRViewController.h"@interface ZQRViewController () <UIScrollViewDelegate>@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;/** * 定時器 */@property (nonatomic, strong) NSTimer *timer;@end@implementation ZQRViewController- (void)viewDidLoad{ [super viewDidLoad]; self.scrollView.delegate=self; // 0.一些固定的尺寸參數 CGFloat imageW = self.scrollView.frame.size.width; CGFloat imageH = self.scrollView.frame.size.height; CGFloat imageY = 0; // 1.添加5張圖片到scrollView中 for (int i = 0; i<MJImageCount; 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 = MJImageCount * 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 = MJImageCount; // 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 == MJImageCount - 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)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ // 停止定時器(一旦定時器停止了,就不能再使用) [self removeTimer];}/** * 停止拖拽的時候調用 */- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ // 開啟定時器 [self addTimer];}@end
ios輪播圖片用法