This article shares the specific code for iOS to automatically switch pictures for your reference. The specific content is as follows
#import "" #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]; = CGSizeMake( * ImageViewCount, 0); = self; = YES;//UIScrollView supports dragging page = ImageViewCount; [self addScrollTimer]; } - (void)rotatePic{ int currentPageIndex = ; if(++currentPageIndex == 5){ currentPageIndex = 0; } CGFloat offsetX = currentPageIndex * ; [UIView animateWithDuration:1 animations:^{ = CGPointMake(offsetX, 0); }]; } /**Add image to imageScrollView*/ - (void)addImageView2ScrollView{ CGFloat imageWidth = ; CGFloat imageHeight = ; for(int i = 0;i <= ImageViewCount;i++){ UIImageView *imageInScroll = [[UIImageView alloc] init]; = CGRectMake(i * imageWidth, 0, imageWidth, imageHeight); = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i + 1]]; [ addSubview:imageInScroll]; } } // Execute while scrolling- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGFloat offX = ;//(0, 0) x-axis length from the upper left vertex inside the content NSLog(@"~~~~~~~%f ^^^^^^%f", offX, ); int currentPageIndex = (offX + .5f * ) / ; = currentPageIndex; } - (void)addScrollTimer{ = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(rotatePic) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer: forMode:NSRunLoopCommonModes]; } - (void)removeScrollTimer{ [ invalidate];//Release timer = nil; } // When you start to prepare for scrolling, remove the timing scrolling operation- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ NSLog(@"~~~scrollViewWillBeginDragging"); [self removeScrollTimer]; } // After ending scrolling, add timed scrolling operation- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ NSLog(@"~~~scrollViewDidEndDragging"); [self addScrollTimer]; } @end
rightUIScrollViewThere are detailed comments in the above code to use it, and 2 points to note:
1. Pay attention to setting the contentSize property. where contentSize represents scroll content size
2. Pay attention to setting the proxy UIScrollViewDelegate before calling the method
forTimer NSTimerUse of
1. Add timer to the loop of the thread
2. Pay attention to using the NSTimer to complete recycling
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.