• 利用UIScrollView和UIPageControl实现多页图片欢迎页面


    在.h文件当中实现UIScrollViewDelegate协议,让控制器充当代理:

    #import <UIKit/UIKit.h>
    
    @interface RPRootViewController : UIViewController <UIScrollViewDelegate>
    
    @property (retain, nonatomic) UIScrollView *scrollView;
    @property (retain, nonatomic) UIPageControl *pageControl;
    
    @end

    实现文件如下:

    #import "RPRootViewController.h"
    
    @interface RPRootViewController ()
    
    @end
    
    @implementation RPRootViewController
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        CGFloat scrollWidth = [[UIScreen mainScreen] bounds].size.width;
        CGFloat scrollHeight = [[UIScreen mainScreen] bounds].size.height;
    
        //定义分页控件
        self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, scrollWidth, 20)];
        self.pageControl.center = CGPointMake(scrollWidth * 0.5, scrollHeight - 80);
        self.pageControl.userInteractionEnabled = NO;
        self.pageControl.numberOfPages = 7;
        self.pageControl.currentPage = 0;
        
        //定义滚动视图
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, scrollWidth, scrollHeight)];
        self.scrollView.contentSize = CGSizeMake(7 * scrollWidth, scrollHeight);
        self.scrollView.pagingEnabled = YES;
        self.scrollView.delegate = self;
        
        //添加7张图片
        for (int i = 1; i <= 7 ; i++) {
            UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(scrollWidth * (i - 1), 0, scrollWidth, scrollHeight)] autorelease];
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img%d.png", i]];
            [self.scrollView addSubview:imageView];
        }
        
        [self.view addSubview:self.scrollView];
        [self.view addSubview:self.pageControl];
    }
    
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        int pageNo = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;
        self.pageControl.currentPage = pageNo;
    }

    首先,先添加滚动视图后添加分页控件,并且禁止分页控件的用户交互,不然视图就不会出现滚动效果了。

    在代理方法当中用偏移量除以控件宽度,可以得到页数。

  • 相关阅读:
    topcoder srm 495 div1
    topcoder srm 500 div1
    topcoder srm 485 div1
    topcoder srm 490 div1
    IDEWorkspaceChecks.plist文件是干什么用的?
    博客推荐
    如何使用U盘安装macOS high Sierra?
    小程序--模板消息调研
    小程序--剖析小程序上传文件
    小程序--小程序开发过程中遇到的问题以及解决方案
  • 原文地址:https://www.cnblogs.com/Steak/p/3741476.html
Copyright © 2020-2023  润新知