Seamless image scrolling components for iOS developers are encapsulated and used, and ios seamless

Source: Internet
Author: User

Seamless image scrolling components for iOS developers are encapsulated and used, and ios seamless

Some Garden friends often ask, "Is there a Demo of Infinite Image scrolling? ", I really don't have a Demo of the picture rolling process. Today, we will encapsulate an image carousel that can be used directly in the project. I have never read any other code for iOS image infinite carousel, and I don't know how they work. I encapsulated this picture infinite carousel today to learn from the Web Front-end practices, because when I wrote the Web Front-end, this is how slides are implemented. Today we are working on the iPhone. The following thing is written by myself, this open source project on carousel is also quite good https://github.com/nicklockwood/iCarousel, interested can look at it. It is quite powerful. Although there is no need to repeat the wheel, it is still necessary to understand the principle. Today's blog introduces a solution for image carousel. Next I will introduce another solution for image carousel.

I. Demo running effect, principle and calling Method

1. Running Effect

The following GIF is the running effect of the Demo. After a certain interval, the image will automatically switch. Of course, finger sliding is also supported. When switching to the corresponding image, click the image, and the Index of the image will be provided through Block callback, and the Index will be provided in the prompt box in the Demo, of course, you can do a lot to get the Index in the project. The Index is the Tag value of the image, that is, the image you clicked on. Three images are in rotation.

1-(void) addZLImageViewDisPlayView {2 3 // obtain the position to be displayed 4 CGRect screenFrame = [[UIScreen mainScreen] bounds]; 5 6 CGRect frame = CGRectMake (10, 60, screenFrame. size. width-20,200); 7 8 NSArray * imageArray = @ [@ "01.jpg", @" 02.jpg", @ "03.jpg"]; 9 10 // initialize the control 11 ZLImageViewDisplayView * imageViewDisplay = [ZLImageViewDisplayView zlImageViewDisplayViewWithFrame: frame WithImages: imageArray]; 12 13 // set the carousel time 14 imageViewDisplay. scrollInterval = 2; 15 16 // The image scrolling time 17 imageViewDisplay. animationInterVale = 0.6; 18 19 // Add the view to the parent view 20 [self. view addSubview: imageViewDisplay]; 21 22 [imageViewDisplay addTapEventForImageWithBlock: ^ (NSInteger imageIndex) {23 NSString * str = [NSString stringWithFormat: @ "I am the % ld image ", imageIndex]; 24 UIAlertView * alter = [[UIAlertView alloc] initWithTitle: @ "prompt" message: str delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; 25 [alter show]; 26}]; 27 28}

 

Ii. Core code Introduction

1. the convenient Initialization Method of the component is as follows. The input parameters are the frame of the component and the array of image names to be displayed. Initialize some attributes and call related initialization methods in convenient initialization methods. The initialization content is as follows:

1 # pragma -- mark traversal initialization method 2-(instancetype) initWithFrame: (CGRect) frame 3 WithImages: (NSArray *) images 4 {5 self = [super initWithFrame: frame]; 6 if (self) {7 // get the width of the rolling view 8 _ widthOfView = frame. size. width; 9 10 // obtain the height of the rolling view 11 _ heightView = frame. size. height; 12 13 _ scrollInterval = 3; 14 15 _ animationInterVale = 0.7; 16 17 // currently displayed page 18 _ currentPage = 1; 19 20 _ imageViewcontentModel = UIViewContentModeScaleAspectFill; 21 22 self. clipsToBounds = YES; 23 24 // initialize the rolling view 25 [self initMainScrollView]; 26 27 // Add ImageView28 [self addImageviewsForMainScrollWithImages: images]; 29 30 // Add timer31 [self addTimerLoop]; 32 33 [self addPageControl]; 34 35} 36 return self; 37}

 

2. Constructor

The constructor is added to our components. The constructor is of course a class method. The passed parameters are the same as the convenient initialization method. This method is mainly used for class initialization, call the convenient initialization method and return the object of the class. The Code is as follows:

# Pragma -- constructor + (instancetype) Syntax: (CGRect) frame WithImages: (NSArray *) images {ZLImageViewDisplayView * instance = [[initalloc] initWithFrame: frame WithImages: images]; return instance ;}

 

3. initialize ScrollView

Add a ScrollView to the custom component view. The size of the ScrollView is the same as that of the custom component. Set the relevant attributes and set the proxy method. The Code is as follows:

1 # pragma -- mark initialize ScrollView 2-(void) preview {3 4 _ mainScrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 0, _ widthOfView, _ heightView)]; 5 6 _ mainScrollView. contentSize = CGSizeMake (_ widthOfView, _ heightView); 7 8 _ mainScrollView. pagingEnabled = YES; 9 10 _ mainScrollView. showsHorizontalScrollIndicator = NO; 11 12 _ mainScrollView. showsVerticalScrollIndicator = NO; 13 14 _ mainScrollView. delegate = self; 15 16 [self addSubview: _ mainScrollView]; 17}

 

4. Add PageControl

Initialize PageControl, configure relevant attributes, and add them to our custom components. The Code is as follows:

1 # Add PageControl 2-(void) addPageControl {3 _ imageViewPageControl = [[UIPageControl alloc] initWithFrame: CGRectMake (0, _ heightView-20, _ widthOfView, 20)]; 4 5 _ imageViewPageControl. numberOfPages = _ imageViewArray. count; 6 7_imageviewpagecontrol. currentPage = _ currentPage-1; 8 9 _ imageViewPageControl. tintColor = [UIColor blackColor]; 10 11 [self addSubview: _ imageViewPageControl]; 12}

 

5. Add ImageView and Image

Add ImageView and Image to ScrollView. The following method is also the core code. We calculate the layout of the Image Frame based on the number of images. The size of each Image is the size of our component, according to the above principle, the first image on the ScrollView is the same as the last image. The first image you want to display is placed in the second image on the ScrollView, and change the Contentoffset of Scollview to display the second image on ScrollView. The Code is as follows:

1 # pragma -- mark add ImageView 2-(void) addImageviewsForMainScrollWithImages: (NSArray *) images {3 // set ContentSize 4 _ mainScrollView. contentSize = CGSizeMake (_ widthOfView * (images. count + 1), _ heightView); 5 6 _ imageViewArray = images; 7 8 for (int I = 0; I <_ imageViewArray. count + 1; I ++) {9 10 CGRect currentFrame = CGRectMake (_ widthOfView * I, 0, _ widthOfView, _ heightView ); 11 12 UIImageView * tempImageView = [[UIImageView alloc] initWithFrame: currentFrame]; 13 14 tempImageView. contentMode = _ imageViewcontentModel; 15 16 tempImageView. clipsToBounds = YES; 17 18 NSString * imageName; 19 20 if (I = 0) {21 imageName = [_ imageViewArray lastObject]; 22} else {23 imageName = _ imageViewArray [I-1]; 24} 25 26 UIImage * imageTemp = [UIImage imageNamed: imageName]; 27 [tempImageView setImage: imageTemp]; 28 29 [_ mainScrollView addSubview: tempImageView]; 30} 31 32 _ mainScrollView. contentOffset = CGPointMake (_ widthOfView, 0); 33 34}

    

6. Add a timer

To make the image work by itself, there is no need for a timer. To add a timer for our component, the following method is to initialize the Timer:

1 - (void) addTimerLoop{2     3     if (_timer == nil) {4         _timer = [NSTimer scheduledTimerWithTimeInterval:_scrollInterval target:self selector:@selector(changeOffset) userInfo:nil repeats:YES];5     }6 }

    

7. Timer execution Method

The following method is the timer execution method. When the time is reached, the ContentOffset. x value of ScrollView is automatically changed, and an animation is used to switch to the next image. If it is the last image, the first image of the ScrollView will be switched to the animation-free mode. Because the first image is the same as the last one, you cannot see the animation-free switch, after switching, the image starts to scroll from the first one, so you can scroll infinitely. The following is the core code:

 1 -(void) changeOffset{ 2      3     _currentPage ++; 4      5     if (_currentPage == _imageViewArray.count + 1) { 6         _currentPage = 1; 7     } 8      9     [UIView animateWithDuration:_animationInterVale animations:^{10         _mainScrollView.contentOffset = CGPointMake(_widthOfView * _currentPage, 0);11     } completion:^(BOOL finished) {12         if (_currentPage == _imageViewArray.count) {13             _mainScrollView.contentOffset = CGPointMake(0, 0);14         }15     }];16     17      _imageViewPageControl.currentPage = _currentPage - 1;18     19 }

 

8. Manual Switch

The above section describes how to enable manual switch for components using NSTimer? To support manual switching, you must process it in the callback of ScrollView. You can do what we want to do in the method after manual sliding, that is, judge whether it is the last image, and then pause the timer. The corresponding callback method is as follows:

 1 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ 2     NSInteger currentPage = scrollView.contentOffset.x / _widthOfView; 3      4     if(currentPage == 0){ 5         _mainScrollView.contentOffset = CGPointMake(_widthOfView * _imageViewArray.count, 0); 6         _imageViewPageControl.currentPage = _imageViewArray.count; 7         _currentPage = _imageViewArray.count; 8     } 9     10     if (_currentPage + 1 == currentPage || currentPage == 1) {11         _currentPage = currentPage;12         13         if (_currentPage == _imageViewArray.count + 1) {14             _currentPage = 1;15         }16         17         if (_currentPage == _imageViewArray.count) {18             _mainScrollView.contentOffset = CGPointMake(0, 0);19         }20         21         _imageViewPageControl.currentPage = _currentPage - 1;22         [self resumeTimer];23         return;24     }25     26     27 }

 

9. Pause the timer.

After manual sliding, You need to pause the timer for a period of time. If you do not pause the timer, you can switch to the next image immediately after manual switching. The following describes how to pause the timer, then, the timer is automatically activated after a period of time. The method is as follows:

1 # pragma pause Timer 2-(void) resumeTimer {3 4 if (! [_ Timer isValid]) {5 return; 6} 7 8 [_ timer setFireDate: [NSDate dateWithTimeIntervalSinceNow: _ scrollInterval-_ animationInterVale]; 9 10}

 

The Code component above can be called, and your image can be used. Finally, the external interface provided by the component is provided:

1 // 2 // ZLImageViewDisplayView. h 3 // ZLImageViewDisplay 4 // 5 // Created by Mr. luDashi on 15/8/14. 6 // Copyright (c) 2015 ludashi. all rights reserved. 7 // 8 9 # import <UIKit/UIKit. h> 10 11 // click the Block callback of the image. The parameter is the index of the current image, that is, the current page number 12 typedef void (^ TapImageViewButtonBlock) (NSInteger imageIndex); 13 14 @ interface ZLImageViewDisplayView: UIView15 16 17 // specifies the time interval for switching an image. Optional. The default value is 3s18 @ property (nonatomic, assign) CGFloat scrollInterval. 19 // specifies the time interval during image switching. Optional, the default value is 0.7s21 @ property (nonatomic, assign) CGFloat animationInterVale; 22 23/********************************** 24 * Function: convenience constructor 25 * parameter: Scroll View Frame, to display the array of the image 26 * return value: 27 **********************************/28 + (instancetype) zlImageViewDisplayViewWithFrame: (CGRect) frame29 WithImages: (NSArray *) images; 30 31/*********************************** 32: convenience initialization function 33 * parameter: Specifies the Frame of the scroll view. 34 * return value of the array of the image to be displayed: 35 ***********************************/36 -(instancetype) initWithFrame: (CGRect) frame37 WithImages: (NSArray *) images; 38 39 40 41/********************************* 42 * function: add the parameter "Click Time 43 *" for each image: Block44 * returned value to be executed by clicking the button: no 45 **********************************/46 -( void) addTapEventForImageWithBlock: (TapImageViewButtonBlock) block; 47 48 @ end

 

  

Iii. Share components and demos

The Demo and component sharing address on GitHub is provided below:

Https://github.com/lizelu/ZLImageViewDisplay

 

The Demo above is one of the solutions for image carousel. The next blog will use two ImageView multiplexing methods to implement the infinite carousel solution for images. The Demo is very anxious to write, and there will inevitably be some leaks. I hope you will criticize and correct me.

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.