The use of UIScorllView and UIPageControl implements the image carousel,

Source: Internet
Author: User

The use of UIScorllView and UIPageControl implements the image carousel,

First, we need to create a project and select Single View Application in the first Application in iOS.

Preparations have been completed. Now we are going to the Main. storyboard Drag Control.

The required controls include:

  • UIScrollView is the rolling one.
  • UIPageControl is the smaller points in the image.
  • NSTimer

Step 1: Drag Control lines

  • Drag a UIScrollView on the Main. storyboard and put it on the screen. Put a UIPageControl under UIScrollView (note that the following is not put on UIscrollView. If it is put on UIScrollView, The UIPageControl will not be seen)
  • Connect to @ interface ViewController () and @ end in ViewController. m.
#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;@end

Step 2:Next we will add a UIImageView to the scrollView in viewdidlevels. At the same time, we need to put 5 Images in Images. xcassets. The Code is as follows:

// Ad image count int count = 5; CGSize size = self. scrollView. frame. size; for (int I = 0; I <count; I ++) {NSString * imageName = [NSString stringWithFormat: @ "img _ % 02d", I + 1]; UIImage * image = [UIImage imageNamed: imageName]; UIImageView * iconView = [[UIImageView alloc] initWithImage: image]; [self. scrollView addSubview: iconView]; // set frame CGFloat x = I * size. width; iconView. frame = CGRectMake (x, 0, size. width, size. height );}

Note that the size of the five uiimageviews is the same as that of the width and height. The difference is that the size of the five uiimageviews is X, and the size of one image is arranged in the back

Step 3:Set the scrollView scroll range and set pagination. The Code is as follows:

// Set the scroll range self. scrollView. contentSize = CGSizeMake (count * size. width, 0); // the scroll bar does not display self. scrollView. showsHorizontalScrollIndicator = NO; self. scrollView. showsVerticalScrollIndicator = NO; // set the page self. scrollView. pagingEnabled = YES; // set pagecontrol self. pageControl. numberOfPages = count;

In the code above, the two lines of code are not displayed because UIScrollView has a horizontal and vertical scroll bars by default. The two lines of code do not display the horizontal and vertical scroll bars, respectively, make sure to set pagination for scrollView. Otherwise, the page splitter will not follow, and the page number of pageControl will be set.

Step 4: Set the scorllView proxy. You should be familiar with the proxy. First, follow the proxy code below @ interface ViewController ().
@ Interface ViewController () <UIScrollViewDelegate>
Then, in viewdidlevels, set who follows the proxy. The ViewController code is as follows:

// Set proxy self. scrollView. delegate = self;

Now we can implement the UIScrollView proxy method.
We need to use three proxy methods:

The first is the method called during scrollView scrolling, the second is the method called when the drag is started, and the third is the method called when the drag is ended.

First, we first want to see if we can drag more than half of scrollView to the next image. The answer is yes. The Code is as follows:

// When scrolling-(void) scrollViewDidScroll :( UIScrollView *) scrollView {int page = (scrollView. contentOffset. x + scrollView. frame. size. width/2)/scrollView. frame. size. width; self. pageControl. currentPage = page ;}

Here, we calculate the page number. We are very familiar with the calculation of the number of pages. For example, 112/10 equals to 11, which means we can calculate the displayed page by size, by the way, I forgot what contentOffset means. This can be understood as the drag distance.

Step 5:To enable the timer function to automatically flip pages, first define a timer code in @ interface ViewController () @ end as follows:

@property (nonatomic, strong) NSTimer *timer; 

Some people may ask why we need to define this, because more than one method needs to use this timer.

Define a timer method. The Code is as follows:

-(Void) addTimer {NSTimer * timer = [nst1_timerwithtimeinterval: 2.0 target: self selector: @ selector (nextImage) userInfo: nil repeats: YES]; self. timer = timer; // messageserole * runLoop = [nsunloop currentRunLoop]; [runLoop addTimer: timer forMode: nsunloopcommonmodes];}

This is a timer method, which creates a timer and adds it to the message loop. In this case, you need to set the method to be executed after the timer is 2 seconds, obviously, we need to turn the page 2 seconds later, so let's write down this method nextImage. The Code is as follows:

-(Void) nextImage {// the current page number NSInteger page = self. pageControl. currentPage; if (page = self. pageControl. numberOfPages-1) {page = 0;} else {page ++;} CGFloat offsetX = page * self. scrollView. frame. size. width; [UIView animateWithDuration: 1.0 animations: ^ {self. scrollView. contentOffset = CGPointMake (offsetX, 0) ;}] ;}

In this method, first define a page to save the current page, and then judge that if the last one is to change the page to 0 (this is not perfect, it will directly go back to the first one from the last one, but the instructor I learned the video didn't provide a solution.) If we set the number of pages after adding 1 to the page, we need to make the page scroll automatically. Then we can set the offset of the scrollView, define offsetX equal to the number of pages multiplied by the width of scrollView, so that you can move to the next view and add an animation to the move.

Call this method in viewdidlevels. The Code is as follows:

[self addTimer];

Step 6:The following shows the UIScrollView proxy method. Two proxy methods are not implemented, that is, the drag and drop method is started and the drag and drop method is ended. The Code is as follows:

// Call-(void) scrollViewWillBeginDragging when you start dragging: (UIScrollView *) scrollView {// stop the timer [self. timer invalidate];} // call-(void) scrollViewDidEndDragging when dragging the end: (UIScrollView *) scrollView willDecelerate :( BOOL) decelerate {[self addTimer];}

The start of the drag here is to stop the timer, otherwise you will flip the page if you do not move it. If you want to stop the timer and stop the timer, we will let it work, you need to enable it and start the timer at the end of the drag.

If you have reached this step, congratulations! Your image carousel is ready!

The complete code is as follows:

# Import "ViewController. h "@ interface ViewController () <strong> @ property (weak, nonatomic) IBOutlet UIScrollView * scrollView; @ property (weak, nonatomic) IBOutlet UIPageControl * pageControl; @ property (nonatomic, strong) NSTimer * timer; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // The total number of AD images int count = 5; CGSize size = self. scrollView. frame. size; for (int I = 0; I <count; I ++) {NSString * imageName = [NSString stringWithFormat: @ "img _ % 02d", I + 1]; UIImage * image = [UIImage imageNamed: imageName]; UIImageView * iconView = [[UIImageView alloc] initWithImage: image]; [self. scrollView addSubview: iconView]; // set frame CGFloat x = I * size. width; iconView. frame = CGRectMake (x, 0, size. width, size. height);} // set the scroll range self. scrollView. contentSize = CGSizeMake (count * size. width, 0); // the scroll bar does not display self. scrollView. showsHorizontalScrollIndicator = NO; self. scrollView. showsVerticalScrollIndicator = NO; // set the page self. scrollView. pagingEnabled = YES; // set pagecontrol self. pageControl. numberOfPages = count; // sets the proxy self. scrollView. delegate = self; [self addTimer];}-(void) addTimer {NSTimer * timer = [nst1_timerwithtimeinterval: 2.0 target: self selector: @ selector (nextImage) userInfo: nil repeats: YES]; self. timer = timer; // messageserole * runLoop = [nsunloop currentRunLoop]; [runLoop addTimer: timer forMode: nsunloopcommonmodes];}-(void) nextImage {// the current page number NSInteger page = self. pageControl. currentPage; if (page = self. pageControl. numberOfPages-1) {page = 0;} else {page ++;} CGFloat offsetX = page * self. scrollView. frame. size. width; [UIView animateWithDuration: 1.0 animations: ^ {self. scrollView. contentOffset = CGPointMake (offsetX, 0) ;}] ;}# pragma mark-scrollView proxy method // when scrolling-(void) scrollViewDidScroll :( UIScrollView *) scrollView {int page = (scrollView. contentOffset. x + scrollView. frame. size. width/2)/scrollView. frame. size. width; self. pageControl. currentPage = page;} // call-(void) scrollViewWillBeginDragging (UIScrollView *) scrollView {// stop the timer [self. timer invalidate];} // call-(void) scrollViewDidEndDragging when dragging the end: (UIScrollView *) scrollView willDecelerate :( BOOL) decelerate {[self addTimer];} @ end

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.