您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么在iOS中實現一個圖片自動切換效果,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
具體內容如下
#import "ViewController.h" #define ImageViewCount 5 @interface ViewController ()<UIScrollViewDelegate> @property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView; @property (weak, nonatomic) IBOutlet UIPageControl *imageViewPageControl; @property (strong, nonatomic) NSTimer *timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self addImageView2ScrollView]; self.imageScrollView.contentSize = CGSizeMake(self.imageScrollView.frame.size.width * ImageViewCount, 0); self.imageScrollView.delegate = self; self.imageScrollView.pagingEnabled = YES;//UIScrollView支持拖動分頁 self.imageViewPageControl.numberOfPages = ImageViewCount; [self addScrollTimer]; } - (void)rotatePic{ int currentPageIndex = self.imageViewPageControl.currentPage; if(++currentPageIndex == 5){ currentPageIndex = 0; } CGFloat offsetX = currentPageIndex * self.imageScrollView.frame.size.width; [UIView animateWithDuration:1 animations:^{ self.imageScrollView.contentOffset = CGPointMake(offsetX, 0); }]; } /**添加圖片到imageScrollView*/ - (void)addImageView2ScrollView{ CGFloat imageWidth = self.imageScrollView.frame.size.width; CGFloat imageHeight = self.imageScrollView.frame.size.height; for(int i = 0;i <= ImageViewCount;i++){ UIImageView *imageInScroll = [[UIImageView alloc] init]; imageInScroll.frame = CGRectMake(i * imageWidth, 0, imageWidth, imageHeight); imageInScroll.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i + 1]]; [self.imageScrollView addSubview:imageInScroll]; } } // 正滾動時執行 - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGFloat offX = self.imageScrollView.contentOffset.x;//(0,0)距離content內部左上頂點的x軸長度 NSLog(@"~~~~~~~%f ^^^^^^%f", offX, self.imageScrollView.frame.size.width); int currentPageIndex = (offX + .5f * self.imageScrollView.frame.size.width) / self.imageScrollView.frame.size.width; self.imageViewPageControl.currentPage = currentPageIndex; } - (void)addScrollTimer{ self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(rotatePic) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } - (void)removeScrollTimer{ [self.timer invalidate];//釋放定時器 self.timer = nil; } // 開始準備滾動時執行 移除定時滾動操作 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ NSLog(@"~~~scrollViewWillBeginDragging"); [self removeScrollTimer]; } // 結束滾動后執行 添加定時滾動操作 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ NSLog(@"~~~scrollViewDidEndDragging"); [self addScrollTimer]; } @end
上述就是小編為大家分享的怎么在iOS中實現一個圖片自動切換效果了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。