////ZQRVIEWCONTROLLER.M//04-Photo Carousel////Created by Apple on 17-08-24.//Copyright (c) 2017 zzqqrr. All rights reserved.//#defineZqrimagecount 5#import "ZQRViewController.h"@interfaceZqrviewcontroller () <UIScrollViewDelegate>@property (Weak, nonatomic) Iboutlet Uiscrollview*ScrollView, @property (weak, nonatomic) Iboutlet Uipagecontrol*Pagecontrol;/** * Timer*/@property (nonatomic, strong) Nstimer*timer;@end@implementationZqrviewcontroller- (void) viewdidload{[Super Viewdidload]; Self.scrollview.Delegate=Self ; //0. Some fixed size parametersCGFloat Imagew =Self.scrollView.frame.size.width; CGFloat Imageh=Self.scrollView.frame.size.height; CGFloat Imagey=0; //1. Add 5 photos to ScrollView for(inti =0; i<mjimagecount; i++) {Uiimageview*imageview =[[Uiimageview alloc] init]; //Set FrameCGFloat ImageX = i *Imagew; Imageview.frame=CGRectMake (ImageX, Imagey, Imagew, Imageh); //set up a pictureNSString *name = [NSString stringWithFormat:@"img_0%d", i +1]; Imageview.image=[UIImage Imagenamed:name]; [Self.scrollview Addsubview:imageview]; } //2. Set the content sizeCGFloat CONTENTW = Mjimagecount *Imagew; Self.scrollView.contentSize= Cgsizemake (CONTENTW,0); //3. Hide the horizontal scroll barSelf.scrollView.showsHorizontalScrollIndicator =NO; //4. Pagingself.scrollView.pagingEnabled =YES;//self.scrollView.delegate = self; //5. Set the total number of pages for PagecontrolSelf.pageControl.numberOfPages =Mjimagecount; //6. Add a timer (call the self's NextImage method every 2 seconds)[self addtimer];}/** * Add timer*/- (void) addtimer{Self.timer= [Nstimer scheduledtimerwithtimeinterval:2.0target:self selector: @selector (nextimage) Userinfo:nil Repeats:yes]; [[Nsrunloop Currentrunloop] AddTimer:self.timer formode:nsrunloopcommonmodes];}/** * Removal timer*/- (void) removetimer{[Self.timer invalidate]; Self.timer=Nil;}- (void) nextimage{//1. Increase the page number of Pagecontrol intpage =0; if(Self.pageControl.currentPage = = Mjimagecount-1) {page=0; } Else{page= Self.pageControl.currentPage +1; } //2. Calculate the position of the ScrollView scrollCGFloat OffsetX = page *Self.scrollView.frame.size.width; Cgpoint Offset= Cgpointmake (OffsetX,0); [Self.scrollview Setcontentoffset:offset animated:yes];}#pragmaMark-Proxy method/** * When ScrollView is scrolling, it will be called*/- (void) Scrollviewdidscroll: (Uiscrollview *) scrollview{//depending on the scroll position of the ScrollView, Pagecontrol displays the first pageCGFloat SCROLLW =ScrollView.frame.size.width; intpage = (scrollview.contentoffset.x + scrollw *0.5) /SCROLLW; Self.pageControl.currentPage=page;}/** * Call when starting a drag*/- (void) Scrollviewwillbegindragging: (Uiscrollview *) scrollview{//Stop timer (once the timer is stopped, it can no longer be used)[self removetimer];}/** * Call when stop dragging*/- (void) Scrollviewdidenddragging: (Uiscrollview *) ScrollView willdecelerate: (BOOL) decelerate{//Turn on Timer[self addtimer];}@end
iOS Carousel Picture Usage