UIScrollView无缝滚动

本文介绍了在iOS开发中实现UIScrollView无缝滚动的需求,通过创建额外的视图并调整偏移量来模拟无缝效果。作者在实践中遇到问题,并参考网络资料进行优化,最终整理出清晰的实现方案。

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

工程里遇到了无缝滚动的需求,自己尝试着写了下,原理基本就是通过多建2个imageView,一个放在最前,一个放在最后,然后通过偏移量判断,[scrollView setContentOffset: animated:NO]; 或者 [scrollView scrollRectToVisible: animated:NO];再通过此方法改变位置实现,最后发现怎么都不能真正的无缝。
上网查了资料,原理虽然跟我原理一样,但处理的比我好很多,不过整理的太乱,于是想整理清楚分享给大家,本无颜称为原创,但毕竟自己原理无错,也是自己整理的,就脸厚了一下。

#define WIDTH 375   //页面宽
#define HEIGHT 400   //页面高

创建ScrollView

@interface ViewController ()
{
    NSMutableArray *imageArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT)];
    self.scrollView.bounces = YES;  //是否允许弹性滑动
    self.scrollView.pagingEnabled = YES;   //设置是否分页
    self.scrollView.delegate = self;    //代理
    self.scrollView.userInteractionEnabled = YES;  //交互性

    imageArray = [[NSMutableArray alloc] init];
    [imageArray addObject:@"image1"];
    [imageArray addObject:@"image2"];
    [imageArray addObject:@"image3"];
    [imageArray addObject:@"image4"];
    [imageArray addObject:@"image5"];

    //添加最后一张图片到第一个位置
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:([imageArray count]-1)]]];
    imageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    [self.scrollView addSubview:imageView];

    for (int i = 0;i<[imageArray count];i++) {
        //loop this bit
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:i]]];
        imageView.frame = CGRectMake((WIDTH * i) + 320, 0, WIDTH, HEIGHT);
        [self.scrollView addSubview:imageView];

        //
    }

    //添加第一张图片到第最后一个位置
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:0]]];
    imageView.frame = CGRectMake((WIDTH * ([imageArray count] + 1)), 0, WIDTH, HEIGHT);
    [self.scrollView addSubview:imageView];


    [self.scrollView setContentSize:CGSizeMake(WIDTH * ([imageArray count] + 2), HEIGHT)];
    [self.scrollView setContentOffset:CGPointMake(0, 0)];
    [self.view addSubview:self.scrollView];
    [self.scrollView scrollRectToVisible:CGRectMake(WIDTH,0,WIDTH,HEIGHT) animated:NO];

}

最后也是关键的一步了,在协议方法里面判断

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
      CGPoint point=scrollView.contentOffset;
     if ((int)point.x==0) {
        [self.scrollView scrollRectToVisible:CGRectMake(WIDTH * [imageArray count],0,WIDTH,HEIGHT) animated:NO];
    } else if ((int)point.x==([imageArray count]+1)*WIDTH) {
        [self.scrollView scrollRectToVisible:CGRectMake(WIDTH,0,WIDTH,HEIGHT) animated:NO];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值