用 UIScrollView 实现图片循环显示

本文介绍如何自定义一个UIScrollView子类,实现循环滚动显示图片的功能。通过维护一个可变数组来存放UIImage对象,并利用三个UIImageView实现平滑过渡的图片浏览效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义一个继承自 UIScrollView的类,将一个可变数组作为公有变量,可在外部往数组中加入多个 UIImage。

@property (nonatomic ,strong)NSMutableArray *imageArray;

其它设置:

#define SELFWIDTH self.frame.size.width
#define SELFHEIGHT SELFWIDTH/800 * 450
static NSUInteger currentImageNum = 1;

设置 imageArray 的 setter。

#pragma mark - 预设三张图片
- (void)setImageArray:(NSMutableArray *)imageArray
{
    _imageArray = imageArray;

    _leftImageView.image   = _imageArray[0];
    _centerImageView.image = _imageArray[1];
    _rightImageView.image  = _imageArray[2];
}

循环滚动三个 UIImageView 达到浏览图片的效果。

@implementation XXScrollVeiw{
    //循环滚动的三个视图
    UIImageView * _leftImageView;
    UIImageView * _centerImageView;
    UIImageView * _rightImageView;
}

初始化

- (void)setup{

    //添加三个 imageView,用于显示图片
    _leftImageView  = [[UIImageView alloc]initWithFrame:
                            CGRectMake(0, 0, SELFWIDTH, SELFHEIGHT)];

    _centerImageView = [[UIImageView alloc]initWithFrame:
                            CGRectMake(SELFWIDTH, 0,SELFWIDTH, SELFHEIGHT)];

    _rightImageView  = [[UIImageView alloc]initWithFrame:
                            CGRectMake(SELFWIDTH * 2, 0,SELFWIDTH, SELFHEIGHT)];

    //设置 contentSize
    self.contentSize = CGSizeMake(SELFWIDTH * 3, SELFHEIGHT);

    //一页一页地滑动
    self.pagingEnabled = YES;

    //scrollView 委托,需在 interface 加上<UIScrollViewDelegate>
    self.delegate = self;

    [self addSubview:_leftImageView];
    [self addSubview:_centerImageView];
    [self addSubview:_rightImageView];
}

实现 UIScrollViewDelegate 中的 scrollViewDidEndDecelerating: 方法。

#pragma mark - 滑动减速完成时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.contentOffset.x == 0)
    {
        currentImageNum = (currentImageNum - 1) % _imageArray.count;
    }
    else if(self.contentOffset.x == SELFWIDTH * 2)
    {
        currentImageNum = (currentImageNum + 1) % _imageArray.count;
    }
    else
    {
        return;
    }

    _leftImageView.image  = _imageArray[(currentImageNum - 1) % _imageArray.count];
    _centerImageView.image = _imageArray[currentImageNum % _imageArray.count];
    _rightImageView.image  = _imageArray[(currentImageNum + 1) % _imageArray.count];


    self.contentOffset = CGPointMake(SELFWIDTH, 0);
}

转载于:https://www.cnblogs.com/huaike/p/4795225.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值