利用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;
}

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

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

 

转载于:https://www.cnblogs.com/Steak/p/3741476.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值