UIScrollView实现滑动图片

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
{
    UIPageControl *_pageControl;
    UIScrollView *_scrollView;
}
@end

//宏定义view的宽和高
#define Mwidth  self.view.frame.size.width
#define Mheight self.view.frame.size.height

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    //----------------------------scrollView-----------------------------
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    //添加到视图
    [self.view addSubview:_scrollView];
    //添加图片
    for (int i = 0; i < 5; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, i*Mheight, Mwidth, Mheight)];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"scene%d.jpg", i+1]];
        [_scrollView addSubview:imageView];
    }
    //总尺寸大小
    _scrollView.contentSize = CGSizeMake(Mwidth, Mheight*5);
    //分页属性打开
    _scrollView.pagingEnabled = YES;
    //反弹效果关闭
    _scrollView.bounces = NO;
    //设置代理,签署UIScrollViewDelegate协议
    _scrollView.delegate = self;

    //-----------------------pageControl-------------------
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, Mheight*7/8, Mwidth, Mheight/8)];
    //非当前页的指示器颜色
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    //添加页数控制器到视图
    [self.view insertSubview:_pageControl aboveSubview:_scrollView];
    //总页数
    _pageControl.numberOfPages = _scrollView.subviews.count;
    //添加事件方法
    [_pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
}

//实现pageControlAction
-(void)pageControlAction:(UIPageControl *)pageControl{
    //显示的图片根据页数变化
    _scrollView.contentOffset = CGPointMake(0,pageControl.currentPage * Mheight);
}
//实现代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //页数随着显示的图片变化
    _pageControl.currentPage = scrollView.contentOffset.y / Mheight;
}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值