iOS Infinite loop scrolling ScrollView

Source: Internet
Author: User

Often have the park friend will ask "Bo Master, there is no picture infinite scrolling demo ah?" ", Serious's picture scrolling demo I really don't have it here today. Encapsulates a picture carousel that you can use directly in your project. No other iOS pictures infinite Carousel code, nor understand their principles, I encapsulate this image today infinite carousel is the practice in the Web front-end, because before the Web front-end when the implementation of the slideshow is doing, today on the iphone to engage in. The following things are written by themselves, about the carousel of things this open source project is also quite good https://github.com/nicklockwood/iCarousel, interested can see. It is quite powerful, although there is no need to repeat the wheel but the principle is necessary to understand. Today's blog on the introduction of a picture carousel solution, the next blog in the introduction of another kind of picture carousel solution.

First, the demo operation effect, principle and call mode

1. Operation effect

The following GIF is the demo running effect, after a certain interval, the picture will automatically switch, of course, also support finger swipe. When switching to the corresponding picture, click on the image, the block callback will give the image of the index, in the demo using the indicator box to give index, of course, in the project to get index you can do a lot of things, index is the tag value of the picture, That is the image that marks the one you clicked. There are three pictures in the carousel.

2. Principle

The following is the implementation of the image of infinite rotation of the schematic diagram (drawing on the Web front-end slide, welcome to put forward a good solution), the principle is summed up in a word: If the 3 images displayed, on the ScrollView on the Paste 4 picture sequence is 3-1-2-3. First show 1 position, then swipe, and so on until the last 3 o'clock, no animation switch to the first 3 position, and then scroll. The schematic diagram below allows you to lay out and instantiate the control according to the following schematic diagram.

3. How components are called

The following code is the initialization of the component and the setting of the property, divided into the following sections:

(1): Determine the location of the component

(2): Create an array of picture names

(3): Initialize the control by facilitating the constructor and pass in the imagename array

(4): Set properties (optional), scrollinterval-picture switch interval, animationintervale-picture motion time

(5): Addtapeventforimagewithblock: The callback after the picture is clicked

 1-(void) addzlimageviewdisplayview{2 3//Get the position to be displayed 4 cgrect screenframe = [[UIScreen mainscreen] bounds]; 5 6 CGRect frame = CGRectMake (ten, screenframe.size.width-20, 200); 7 8 Nsarray *imagearray = @[@ "01.jpg", @ "02.jpg", @ "03.jpg"]; 9 10//Initialize control one by one zlimageviewdisplayview *imageviewdisplay = [Zlimageviewdisplayview ZLIMAGEVIEWDISPLAYVIEWWITHFR Ame:frame withimages:imagearray];12 13//Set the carousel time Imageviewdisplay.scrollinterval = 2;15 16//Picture scrolling time 1 7 Imageviewdisplay.animationintervale = 0.6;18 19//Add the view to the corresponding parent view [Self.view Addsubview:imageviewdispla y];21 [Imageviewdisplay addtapeventforimagewithblock:^ (Nsinteger imageindex) {nsstring *str = [NSStr ing stringwithformat:@ "I am the first%ld picture", imageindex];24 uialertview *alter = [[Uialertview alloc] initwithtitle:@ "hint" me     Ssage:str delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil, nil];25 [Alter SHOW];26}];2728} 

Second, the core code introduction

1. The convenient initialization method of the component is as follows, the passed parameter is the component frame, and the image name array to display. Initialize some properties and invoke related initialization methods in the convenience initialization method. The initialization content is as follows:

1 #pragma--mark traversal initialization Method 2-(Instancetype) initWithFrame: (CGRect) Frame 3                withimages: (Nsarray *) Images 4 {5     SE LF = [Super Initwithframe:frame]; 6     if (self) {7         //Gets the width of the scrolling view 8         _widthofview = frame.size.width; 9         //Gets the height of the scroll view one by one         _heightview = frame.size.height;12         _scrollinterval = 3;14         _animationintervale = 0.7;16         // Current Display page         _currentpage = 1;19         _imageviewcontentmodel = uiviewcontentmodescaleaspectfill;21         self.clipstobounds = yes;23         //Initialize scrolling view         [self initmainscrollview];26         // Add ImageView28         [self addimageviewsformainscrollwithimages:images];29         //Add timer31         [self Addtimerloop];32         [self addpagecontrol];34     }36     return self;37}

2. Convenience Builder

To add a convenient constructor for our components, the constructor is of course a class method, and the method of passing parameters is the same as facilitating the initialization method, which is basically the initialization of the class, then invoking the convenient initialization method and returning the object of the class. The code is as follows:

#pragma--Convenience builder + (Instancetype) Zlimageviewdisplayviewwithframe: (cgrect) frame                                      withimages: (Nsarray *) images{    Zlimageviewdisplayview *instance = [[Zlimageviewdisplayview alloc] Initwithframe:frame withimages:images];    return instance;}

3. Initialize ScrollView

To add ScrollView to our custom component view, the size of the ScrollView is the same as the size of our custom component, and the relevant properties are set, the proxy method is set, and the code is as follows:

1 #pragma--Mark Initialize ScrollView 2-(void) initmainscrollview{3      4     _mainscrollview = [[Uiscrollview alloc] Initwit Hframe:cgrectmake (0, 0, _widthofview, _heightview)]; 5      6     _mainscrollview.contentsize = Cgsizemake (_widthofview, _heightview); 7      8     _ mainscrollview.pagingenabled = YES; 9     _mainscrollview.showshorizontalscrollindicator = no;11     _ Mainscrollview.showsverticalscrollindicator = no;13     _mainscrollview.delegate = self;15     [ Self addsubview:_mainscrollview];17}

4. Add Pagecontrol

Initialize the Pagecontrol, configure the relevant properties, and add to our custom component, the code is as follows:

1 #pragma add Pagecontrol 2-(void) addpagecontrol{3     _imageviewpagecontrol = [[Uipagecontrol alloc] Initwithframe:cgr Ectmake (0, _heightview-20, _widthofview, 20)]; 4      5     _imageviewpagecontrol.numberofpages = _imageviewarray.count; 6      7     _ Imageviewpagecontrol.currentpage = _currentpage-1; 8      9     _imageviewpagecontrol.tintcolor = [Uicolor blackcolor];10     [self addsubview:_ IMAGEVIEWPAGECONTROL];12}

5. Add ImageView and image

Add ImageView and image to ScrollView, the following method is also the core code, we are based on the number of pictures to calculate the frame of the picture to layout, each picture size is the size of our components, according to the principle of the above introduction, ScrollView on the first picture and the last picture, you want to display the first picture on the ScrollView on the second sheet, and change Scollview contentoffset display the second picture on the ScrollView, the code is as follows:

 1 #pragma-Mark adds ImageView 2-(void) addimageviewsformainscrollwithimages to ScrollView: (Nsarray *) images{3//SET CO Ntentsize 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 CGRect currentframe = CGRECTM Ake (_widthofview * I, 0, _widthofview, _heightview); Uiimageview *tempimageview = [[Uiimageview alloc         ] initwithframe:currentframe];13 Tempimageview.contentmode = _imageviewcontentmodel;15 16             Tempimageview.clipstobounds = yes;17 NSString *imagename;19 if (i = = 0) {21         ImageName = [_imageviewarray lastobject];22} else {imageName = _imageviewarray[i-1];24 }25 UIImage *imagetemp = [UIImage imagenamed:imagename];27 [Tempimageview setimage:imaget Emp];28 [_mainscrollview addsubview:tempimageview];30}31 _mainscrollview.contentoffset = C Gpointmake (_widthofview, 0); 33 34}

    

6. Adding timers

Want to let the picture itself move, is the timer, for our components to add timers, the following method is the initialization timer method:

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. How the timer executes

The following method is the timer execution method, when the time comes, automatically change the value of ScrollView contentoffset.x, there is animation to switch to the next picture. If the current is the last picture is not animated switch to scrollview the first picture, because the first picture and the last picture is the same, so the user does not see this no animation switch, after the switch, the picture starts from the first start scrolling, so you can infinite cycle of scrolling, The following is also the core code:

1-(void) changeoffset{2      3     _currentpage + + 4      5     if (_currentpage = = _imageviewarray.count + 1) {6         _c Urrentpage = 1; 7     } 8      9     [UIView Animatewithduration:_animationintervale animations:^{10         _ Mainscrollview.contentoffset = Cgpointmake (_widthofview * _currentpage, 0);     completion:^ (BOOL finished) {12         if (_currentpage = = _imageviewarray.count) {             _mainscrollview.contentoffset = cgpointmake (0, 0);     }];16      _imageviewpagecontrol.currentpage = _currentpage-1;18     19}

8. Manually switch

The above is the use of Nstimer to achieve automatic switching, then how to let the component support manual switch it? Support for manual switching is handled in our ScrollView callback. After the user manually swipe the method to do what we want to do is to determine whether the last picture, 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     if (_currentpage + 1 = = CurrentPage | | currentpage = 1) {         _currentpage = currentpage;12         F (_currentpage = = _imageviewarray.count + 1) {             _currentpage = 1;15         }16         if (_currentpage = = _ima Geviewarray.count) {             _mainscrollview.contentoffset = cgpointmake (0, 0);         }20         _ Imageviewpagecontrol.currentpage = _currentpage-1;22         [self resumetimer];23         return;24     }25     26     27}

9. Pause Timer

After manual sliding to pause the timer for a period of time, because no pause, you manually switch over, sometimes immediately switch to the next picture, the following is the way to pause the timer, and then after a period of time to automatically activate the timer. Methods are 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}

After the code component above can be called, your image can be used, and finally give the component to set aside the external interface:

 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 on the image's block callback, the index of the current picture, that is, the current page of a typedef void (^tapimageviewbuttonblock) ( Nsinteger imageindex) @interface ZLIMAGEVIEWDISPLAYVIEW:UIVIEW15 16 17//Toggle picture interval, optional, default to 3s18 @property (Nonatomi C, assign) CGFloat scrollinterval;19 20//Toggle picture, motion interval, optional, default to 0.7s21 @property (nonatomic, assign) cgfloat animationintervale;22 23/**********************************24 * Function: Convenient constructor 25 * parameter: Scrolling view of frame, to display the image of the array 26 * return value: Object 27 of the class * *                                       /28 + (Instancetype) Zlimageviewdisplayviewwithframe: (CGRect) frame29 Withimages: (Nsarray *) images;30 31/**********************************32 * Function: Convenient initialization function 33 * Parameter: Scroll view of FRA            Me, to display an array of pictures 34 * Return Value: Object of this class **********************************/36-(Instancetype) initWithFrame: (CGRect) frame37        Withimages: (Nsarray *) images;38 39 40 41/**********************************42 * Function: Add click time for each picture 43 * Parameters: Click on the button to execute the B LOCK44 * return value: No **********************************/46-(void) Addtapeventforimagewithblock: ( Tapimageviewbuttonblock) block;47 @end

  

Three. Components and demo sharing

The following shows the demo and component sharing addresses on GitHub:

Https://github.com/lizelu/ZLImageViewDisplay

The demo above is one of the solutions to the picture carousel, and the next blog will use two ImageView to implement the infinite carousel solution for the picture. Demo write more anxious, inevitably there will be flaws in the place, hope everyone criticize correct.

Transferred from: http://www.cnblogs.com/ludashi/p/4741384.html

iOS Infinite loop scrolling ScrollView

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.