[iOS]通过UIScrollView和UIPageControl实现滑动切换的效果

UIPageControl是自带的控件,可以查看官方文档,下载官方示例学习。

如果对Xcode自带的文档不熟悉可以参见:苹果Xcode帮助文档阅读指南

接下来是我学习笔记,使用Storyboard实现滑动切换的效果。


-----------------------------------------------------------------------------


新建一个项目,拖上一个UIScrollView和UIPageControl,并且建立关联:



新建一个ContentViewController,作为页面切换的内容视图:




也就是说,当滑动屏幕切换的时候,其实就是多个ContentViewController在切换。


基本结构是:


在主页面,我们首先初始化一些设置:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // 初始化page control的内容
    _contentList = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
    
    
    // 一共有多少页
    NSUInteger numberPages = self.contentList.count;
    
    // 存储所有的controller
    NSMutableArray *controllers = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < numberPages; i++)
    {
		[controllers addObject:[NSNull null]];
    }
    self.viewControllers = controllers;
    
    // 一个页面的宽度就是scrollview的宽度
    self.myScrollView.pagingEnabled = YES;  // 自动滚动到subview的边界
    self.myScrollView.contentSize =
    CGSizeMake(CGRectGetWidth(self.myScrollView.frame) * numberPages, CGRectGetHeight(self.myScrollView.frame));
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.showsVerticalScrollIndicator = NO;
    self.myScrollView.scrollsToTop = NO;
    self.myScrollView.delegate = self;
    
    _numberOfPages = numberPages;
    _myPageControl.numberOfPages = numberPages;
    _currentPage = 0;
    
    
    [self loadScrollViewWithPage:0];
    [self loadScrollViewWithPage:1];
    
}






接下来,我们需要一个函数,来加载ContentView页面上的元素:

// 加载ScrollView中的不同SubViewController
- (void)loadScrollViewWithPage:(NSUInteger)page
{
    if (page >= self.contentList.count)
        return;
    
    // replace the placeholder if necessary
    LContentViewController *controller = [self.viewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null])
    {
        controller = [[LContentViewController alloc] init];
        [self.viewControllers replaceObjectAtIndex:page withObject:controller];
    }
    
    // add the controller's view to the scroll view
    if (controller.view.superview == nil)
    {
        CGRect frame = self.myScrollView.frame;
        frame.origin.x = CGRectGetWidth(frame) * page;
        frame.origin.y = 0;
        controller.view.frame = frame;
        [controller setLabel:[_contentList objectAtIndex:page]];
        [self.myScrollView addSubview:controller.view];
    }
}

然后先来处理一下PageControl的切换事件:

- (void)gotoPage:(BOOL)animated
{
    NSInteger page = self.myPageControl.currentPage;
    
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    [self loadScrollViewWithPage:page + 1];
    
	// update the scroll view to the appropriate page
    CGRect bounds = self.myScrollView.bounds;
    bounds.origin.x = CGRectGetWidth(bounds) * page;
    bounds.origin.y = 0;
    [self.myScrollView scrollRectToVisible:bounds animated:animated];
}

// page control 选项修改监听
- (IBAction)changePage:(id)sender
{
    [self gotoPage:YES];    // YES = animate
}

滑动ScrollView的事件监听:


// 滑动结束的事件监听
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = CGRectGetWidth(self.myScrollView.frame);
    NSUInteger page = floor((self.myScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.myPageControl.currentPage = page;
    NSLog(@"当前页面 = %d",page);
    // a possible optimization would be to unload the views+controllers which are no longer visible
    
    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    [self loadScrollViewWithPage:page + 1];
}
























  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
定时滚动和循环滚动,可点击图片和PageController #import "ASIFormDataRequest.h" #import "GWPublicClass.h" @interface ViewController ()<UIScrollViewDelegate> @end @implementation ViewController { UIScrollView * headScrollView; UIPageControl * pageControl; NSArray * colorArray; NSTimer * myTimer; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } #pragma UIScrollView delegate -(void)scrollToNextPage:(id)sender { int pageNum = pageControl.currentPage; CGSize viewSize = headScrollView.frame.size; CGRect rect = CGRectMake((pageNum+2)*viewSize.width, 0, viewSize.width, viewSize.height); [headScrollView scrollRectToVisible:rect animated:NO]; pageNum++; if (pageNum == colorArray.count) { CGRect newRect=CGRectMake(viewSize.width, 0, viewSize.width, viewSize.height); [headScrollView scrollRectToVisible:newRect animated:NO]; } } -(void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat pageWidth = headScrollView.frame.size.width; int currentPage = floor((headScrollView.contentOffset.x-pageWidth/2)/pageWidth)+1; if (currentPage == 0) { pageControl.currentPage = colorArray.count-1; }else if(currentPage == colorArray.count+1){ pageControl.currentPage=0; } pageControl.currentPage = currentPage-1; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { [myTimer invalidate]; } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { myTimer=[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(scrollToNextPage:) userInfo:nil repeats:YES]; } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { CGFloat pageWidth = headScrollView.frame.size.width; CGFloat pageHeigth = headScrollView.frame.size.height; int currentPage=floor((headScrollView.contentOffset.x-pageWidth/2)/pageWidth)+1; NSLog(@"the current offset==%f",headScrollView.contentOffset.x); NSLog(@"the current page==%d",currentPage); if (currentPage == 0) { [headScrollView scrollRectToVisible:CGRectMake(pageWidth*colorArray.count, 0, pageWidth, pageHeigth) animated:NO]; pageControl.currentPage = colorArray.count-1; NSLog(@"pageControl currentPage==%d",pageControl.currentPage); NSLog(@"the last image"); return; }else if(currentPage == [colorArray count]+1){ [headScrollView scrollRectToVisible:CGRectMake(pageWidth, 0, pageWidth, pageHeigth) animated:NO]; pageControl.currentPage=0; NSLog(@"pageControl currentPage==%d",pageControl.currentPage); NSLog(@"the first image"); return; } pageControl.currentPage=currentPage-1; NSLog(@"pageControl currentPage==%d",pageControl.currentPage); } - (void)pageTurn:(UIPageControl *)sender { int pageNum = pageControl.currentPage; CGSize viewSize = headScrollView.frame.size; [headScrollView setContentOffset:CGPointMake((pageNum+1)*viewSize.width, 0)]; NSLog(@"myscrollView.contentOffSet.x==%f",headScrollView.contentOffset.x); NSLog(@"pageControl currentPage==%d",pageControl.currentPage); [myTimer invalidate]; } - (void)handleTapGesture:(UITapGestureRecognizer*)gesture { NSLog(@"UITapGesture被调用了%d",gesture.view.tag); // ... } - (void)viewDidLoad { [super viewDidLoad]; colorArray = @[[UIColor redColor],[UIColor greenColor],[UIColor blueColor]]; headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 80, 320, 200)]; headScrollView.backgroundColor = [UIColor blackColor]; [self.view addSubview:headScrollView]; CGFloat Width= 320; CGFloat Height= 200; UIImageView * firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Width, Height)]; firstImageView.userInteractionEnabled = YES; firstImageView.tag = 50+colorArray.count-1; firstImageView.backgroundColor = colorArray[colorArray.count-1]; [headScrollView addSubview:firstImageView]; UITapGestureRecognizer * gestd = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; [firstImageView addGestureRecognizer:gestd]; for (int i=0; i<colorArray.count; i++) { UIImageView * subImageView=[[UIImageView alloc] initWithFrame:CGRectMake(Width*(i+1), 0, Width, Height)]; subImageView.backgroundColor = colorArray[i]; subImageView.userInteractionEnabled = YES; subImageView.tag = 50+i; subImageView.frame=CGRectMake(Width*(i+1), 0, Width, Height); [headScrollView addSubview: subImageView]; UITapGestureRecognizer * gestd = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; [subImageView addGestureRecognizer:gestd]; } UIImageView * lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Width*(colorArray.count+1), 0, Width, Height)]; lastImageView.userInteractionEnabled = YES; lastImageView.backgroundColor = colorArray[0]; lastImageView.tag = 50; [headScrollView addSubview:lastImageView]; headScrollView.contentSize = CGSizeMake(Width*(colorArray.count+2), Height); headScrollView.pagingEnabled = YES; headScrollView.delegate = self; [headScrollView scrollRectToVisible:CGRectMake(Width, 0, Width, Height) animated:YES]; pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(100, 290, 120, 20)]; pageControl.numberOfPages = colorArray.count; pageControl.backgroundColor = [UIColor greenColor]; pageControl.enabled = YES; pageControl.currentPage = 0; [pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:pageControl]; myTimer=[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(scrollToNextPage:) userInfo:nil repeats:YES]; } - (void)enterDetail { NSLog(@"tap is "); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值