IOS implements automatic cyclic rolling advertisement-ScrollView optimization and encapsulation, and ios-scrollview

Source: Internet
Author: User

IOS implements automatic cyclic rolling advertisement-ScrollView optimization and encapsulation, and ios-scrollview

I. Problem Analysis

In many apps, we will see a circular scrolling view, such as an advertisement. In fact, it is not difficult to implement this function, and ScrollView can be easily implemented, however, there are still several small problems in the production process. If you can properly handle these small problems, the effects and performance will be optimized.

Question 1

The first problem is how to use ScrollView to display N views. To achieve this effect, you can add N views to the ScrollView in sequence, and set the contentSize of the ScrollView to the size of N views, slide the ScrollView to view the view added above.

Question 2

The second problem is how to complete the circular scrolling of the image, that is, after the last image is displayed, the first image is displayed in a circular manner. To achieve this effect, you first need to enable the ScrollView to implement automatic paging, so that the full view can be displayed after sliding. Secondly, you need to set the contentOffset of the ScrollView based on the number of pages currently displayed.

The solution to the first problem is the simplest method, but it actually ignores a very important problem. If the number of views to be displayed is N, what should we do? Assuming that the width of each view displayed through ScrollView is exactly the width of the screen, we can display at most two views in front of us, that is, either a complete view or two incomplete views. Therefore, we only need to have three views to demonstrate the loop.

Question 3

The third problem is that you want to know the current page number during the cyclic rolling process. The page number can be calculated by contentOffset. x, which is usually expressed by UIPageControl. In addition, when you click a view, you need to know which view is currently clicked.

Question 4

The fourth problem is to automatically display the next page. You need to write the method to jump to the next page, and then use the NSTimer timer.

In addition to the above issues, you can also add more features for it. For general functions such as automatic page flip of ScrollView, the best way is to encapsulate them, which can greatly improve the efficiency. The following code encapsulates UIScrollView and UIPageControl into a UIView, and ScrollView is used to repeatedly display multiple images.

Ii. function implementation
1. encapsulate Scrollview code. h:
// WHScrollAndPageView. h // circular scroll view /// Created by jereh on 15-3-15. // Copyright (c) 2015 jereh. all rights reserved. // # import <UIKit/UIKit. h> @ protocol WHcrollViewViewDelegate; @ interface WHScrollAndPageView: UIView <region >{_ Region id <region> _ delegate;} @ property (nonatomic, assign) id <WHcrollViewViewDelegate> delegate; @ property (nonatomic, assign) NSInteger currentPage; @ property (nonatomic, strong) NSMutableArray * imageViewAry; @ property (nonatomic, readonly) UIScrollView * scrollView; @ property (nonatomic, readonly) UIPageControl * pageControl;-(void) shouldAutoShow :( BOOL) shouldStart; @ end @ protocol publish <NSObject> @ optional-(void) didClickPage :( cursor *) view atIndex :( NSInteger) index; @ end
2. encapsulate Scrollview code. m:
// WHScrollAndPageView. m // circular scroll view /// Created by jereh on 15-3-15. // Copyright (c) 2015 jereh. all rights reserved. // # import "WHScrollAndPageView. h "@ interface WHScrollAndPageView () {UIView * _ firstView; UIView * _ middleView; UIView * _ lastView; float _ viewWidth; float _ viewHeight; NSTimer * _ autoScrollTimer; UITapGestureRecognizer * _ tap;} @ end @ implementation WHScrollAndPageView-(id) initWithFrame :( CGR Ect) frame {self = [super initWithFrame: frame]; if (self) {_ viewWidth = self. bounds. size. width; _ viewHeight = self. bounds. size. height; // set scrollview _ scrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 0, _ viewWidth, _ viewHeight)]; _ scrollView. delegate = self; _ scrollView. contentSize = CGSizeMake (_ viewWidth * 3, _ viewHeight); _ scrollView. showsHorizontalScrollIndicator = NO; _ scrollView. PagingEnabled = YES; _ scrollView. backgroundColor = [UIColor blackColor]; _ scrollView. delegate = self; [self addSubview: _ scrollView]; // set page_pagecontrol = [[UIPageControl alloc] initWithFrame: CGRectMake (0, _ viewHeight-30, _ viewWidth, 30)]; _ pageControl. userInteractionEnabled = NO; _ pageControl. currentPageIndicatorTintColor = [UIColor redColor]; _ pageControl. pageIndicatorTintColor = [UIColor white Color]; [self addSubview: _ pageControl]; // set the click gesture _ tap = [[UITapGestureRecognizer alloc] initWithTarget: self action: @ selector (handleTap :)]; _ tap. numberOfTapsRequired = 1; _ tap. numberOfTouchesRequired = 1; [_ scrollView addGestureRecognizer: _ tap];} return self;} # pragma mark click gesture-(void) handleTap :( UITapGestureRecognizer *) sender {if ([_ delegate respondsToSelector: @ selector (didClickPage: atIndex :)]) {[_ d Elegate didClickPage: self atIndex: _ currentPage + 1] ;}# pragma mark sets imageViewAry-(void) Labels :( NSMutableArray *) imageViewAry {if (imageViewAry) {_ imageViewAry = imageViewAry; _ currentPage = 0; // The default value is 0th page _ pageControl. numberOfPages = _ imageViewAry. count;} [self reloadData] ;}# pragma mark refresh view page-(void) reloadData {[_ firstView removeFromSuperview]; [_ middleView removeFromSuperview]; [_ lastVi Ew removeFromSuperview]; // obtain the corresponding image view from the array and add it to the three defined views if (_ currentPage = 0) {_ firstView = [_ imageViewAry lastObject]; _ middleView = [_ imageViewAry objectAtIndex: _ currentPage]; _ lastView = [_ imageViewAry objectAtIndex: _ currentPage + 1];} else if (_ currentPage = _ imageViewAry. count-1) {_ firstView = [_ imageViewAry objectAtIndex: _ currentPage-1]; _ middleView = [_ imageViewAry objectAtIndex: _ currentPa Ge]; _ lastView = [_ imageViewAry firstObject];} else {_ firstView = [_ imageViewAry objectAtIndex: _ currentPage-1]; _ middleView = [_ imageViewAry objectAtIndex: _ currentPage]; _ lastView = [_ imageViewAry objectAtIndex: _ currentPage + 1];} // set the frame of the three views and add them to the scrollview _ firstView. frame = CGRectMake (0, 0, _ viewWidth, _ viewHeight); _ middleView. frame = CGRectMake (_ viewWidth, 0, _ viewWidth, _ viewHeight); _ la StView. frame = CGRectMake (_ viewWidth * 2, 0, _ viewWidth, _ viewHeight); [_ scrollView addSubview: _ firstView]; [_ scrollView addSubview: _ middleView]; [_ scrollView addSubview: _ lastView]; // sets the current pageControl. currentPage = _ currentPage; // display the Center page _ scrollView. contentOffset = CGPointMake (_ viewWidth, 0);} # pragma mark scrollvie stop slide-(void) scrollViewDidEndDecelerating :( UIScrollView *) scrollView {// pause automatic replacement when sliding manually [_ AutoScrollTimer invalidate]; _ autoScrollTimer = nil; _ autoScrollTimer = [NSTimer metadata: 2 target: self selector: @ selector (autoShowNextImage) userInfo: nil repeats: YES]; // obtain the current page float x = _ scrollView. contentOffset. x; // forward flip if (x <= 0) {if (_ currentPage-1 <0) {_ currentPage = _ imageViewAry. count-1;} else {_ currentPage -- ;}// flip back if (x >=_ viewWidth * 2) {if (_ currentPage = _ ima GeViewAry. count-1) {_ currentPage = 0;} else {_ currentPage ++;} [self reloadData] ;}# pragma mark auto scroll-(void) shouldAutoShow :( BOOL) shouldStart {if (shouldStart) // Enable Automatic paging {if (! _ AutoScrollTimer) {_ autoScrollTimer = [nst1_scheduledtimerwithtimeinterval: 2 target: self selector: @ selector (autoShowNextImage) userInfo: nil repeats: YES];} else // disable automatic paging {if (_ autoScrollTimer. isValid) {[_ autoScrollTimer invalidate]; _ autoScrollTimer = nil ;}}# pragma mark displays the next page-(void) autoShowNextImage {if (_ currentPage ==_ imageViewAry. count-1) {_ currentPage = 0;} else {_ currentPage ++;} [self reloadData];} @ end
3. Use the encapsulated Scrollview code. m:
// ViewController. m // circular scroll view /// Created by jereh on 15-3-15. // Copyright (c) 2015 jereh. all rights reserved. // # import "ViewController. h "# import" WHScrollAndPageView. h "# define NUM 10 @ interface ViewController () <whcrollviewdelegate> {WHScrollAndPageView * _ whView;} @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // create a view (view contains UIScrollView and UIPageControl, set frame) _ whView = [[WHScrollAndPageView alloc] initWithFrame: CGRectMake (0, 44,320,400)]; // place N images on the imageview NSMutableArray * tempAry = [NSMutableArray array]; for (int I = 1; I <NUM; I ++) {UIImageView * imageView = [[UIImageView alloc] init]; imageView. image = [UIImage imageNamed: [NSString stringWithFormat: @ "image% I .jpg", I]; [tempAry addObject: imageView];} // Save the imageView array to whView [_ whView setImageViewAry: tempAry]; // Add the view displayed in the image to the current page [self. view addSubview: _ whView]; // enable automatic page turning [_ whView shouldAutoShow: YES]; // abide by Protocol _ whView. delegate = self ;}# method in The pragma mark protocol, click a page-(void) didClickPage :( WHScrollAndPageView *) view atIndex :( NSInteger) index {NSLog (@ "% li page clicked", index) ;}# when The pragma mark interface disappears, stop auto scroll-(void) viewDidDisappear :( BOOL) animated {[_ whView shouldAutoShow: NO] ;}@ 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.