IOS development (I) carousel and ios

Source: Internet
Author: User

IOS development (I) carousel and ios
Preface

The vast majority of apps on the market are highlighted by a magnificent carousel. Therefore, being able to make a suitable and efficient carousel becomes a necessary skill for programmers. So today's blog will talk about the principles contained in the seemingly simple control of the carousel.

Body

First, let's analyze how to implement a similar carousel (the number of images and URLs are returned by the server ):

    

Policy 1: UIScrollView-> UIImageView-> NSTimer Round Robin is a conventional policy. However, if you think about it, if the server returns 50 images to you, you need to create 50 uiimageviews as containers. This performance is definitely not optimal. Next, all the uiimageviews are arranged in order. If the last image is to be restored to the first image, UIScrollView will be promoted to the first position. Poor results!

Policy 2: Think about the reuse of UITableViewCell. We can also reuse the UIImageView. The three uiimageviews of the carousel are enough. They are divided into CenterImageView, LeftImageView, and RightImageView in the current field of view. The difference is the image switching between them. Next we will try to implement an efficient carousel.

Code Implementation

 

 2. Write a special control to calculate the three serial numbers in the left and right and load them into the corresponding image.

/** Here I name it reloadAllImageView */

-(Void) reloadAllImageView {

CGPoint offset = _ backScrollView. contentOffset;/** obtain the x-axis offset of scroll */

 

If (offset. x = 2 * DeviceWidth) {/** there are two boundary conditions to handle (1 ). from first-> last (2) last-> first */

/** (2 )*/

_ CenterImageIndex = (_ centerImageIndex + 1) % 3;/** 3 indicates the number of images. Here, the homepage type must be strongly converted. _ CenterImageIndex (NSUInteger) is used to record the current image number */

_ PageControl. currentPage = (_ pageControl. currentPage + 1) % 3;

}

Else if (offset. x = 0 ){

/** (1 )*/

If (_ centerImageIndex = 0) {/** a special case where _ centerImageIndex is equal to 0 (_ centerImageIndex-1) % 3 is not the expected result */

_ CenterImageIndex = 3;/** it takes a long time to convert the computing type. Only three images may be faulty. If you are interested, you can perform in-depth research */

}/**-1% 3 = 0. If all the signed results are-1, the result is 0 if the unsigned results are processed. Should the calculation process be performed first by taking the forward bits before calculation? */

_ CenterImageIndex = (_ centerImageIndex-1) % 3;

_ PageControl. currentPage = (_ pageControl. currentPage-1) % 3;

}

_ CenterImageView. image = [UIImage imageNamed: [NSString stringWithFormat: @ "Fig", _ centerImageIndex + 1];

NSUInteger leftImageViewIndex = (_ centerImageIndex-1) % 3;

NSUInteger rightImageViewIndex = (_ centerImageIndex + 1) % 3;

If (leftImageViewIndex = 0 & _ centerImageIndex = 0) {/** handle computing exceptions temporarily as above */

LeftImageViewIndex = 2;

}

_ LeftImageView. image = [UIImage imageNamed: [NSString stringWithFormat: @ "d.d.jpg", leftImageViewIndex + 1];

_ RightImageView. image = [UIImage imageNamed: [NSString stringWithFormat: @ "d.d.jpg", rightImageViewIndex + 1];

}
   3. Now the carousel can be switched normally at the boundary. Now you need to add a timer to automatically slide:

/** Declare a Timer * // ** the reason for using weak: If self has a strong Timer, you need to set the Traget of the Timer and select the sub-selector, timer retains the target object until it becomes invalid. Generate a reserved ring */

@ Property (nonatomic, weak) NSTimer * timer;

/** Timer initialization */

-(Void) initTimer

{

Self. timer = [NSTimer scheduledTimerWithTimeInterval: animationTime target: self selector: @ selector (updateImageView :) userInfo: nil repeats: YES];

}

-(Void) updateImageView :( NSTimer *) timer

{

[_ BackScrollView setContentOffset: CGPointMake (DeviceWidth * 2, 0) animated: YES];

[NSTimer scheduledTimerWithTimeInterval: 0.4f target: self selector: @ selector (scrollViewDidEndDecelerating :) userInfo: nil repeats: NO];

}

/** Load all images and move the middle field of view */

-(Void) scrollViewDidEndDecelerating :( UIScrollView *) scrollView {

// Reload the image

[Self reloadAllImageView];

// Move to the current field of view

[_ BackScrollView setContentOffset: CGPointMake (DeviceWidth, 0)];

// Set the script

_ PageControl. currentPage = _ centerImageIndex;

}

 4. Since then, the carousel has probably taken shape. The rest is the mutex processing of timer and user sliding operations.

/** Record a bool value to determine whether you are willing to perform the slide operation. YES, the timer is triggered, and NO is triggered by the user */

(1). In the timer trigger event, it must be a slide triggered by the timer. So here the bool value is YES.

(2) When loading and replacing images, we need to make a judgment (if the timer is triggered by the user, we need to cancel the timer and set it from null to 0)

 

If (! Bool ){

 

[Self. timer setFireDate: [NSDate dateWithTimeIntervalSinceNow: animationTime];

 

}

 

Bool = NO;

End

As a result, the carousel is implemented, but the problem still needs to be solved <1>. Three images must be restricted or crash <2> is not encapsulated into a separate scrllview for use. These problems may be considered and optimized in the future. It may be a good idea to try UICollection.

Finally, I wrote this blog for a purpose. In fact, if any seemingly simple function needs to be thoroughly explored, I still have some knowledge and I have discovered my own shortcomings. Finally, if you have any thoughts on your blog, please leave a message below. Let's discuss the progress together. Thank you!

 

 

 

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.