iOS:如何使用分页滑动图像

Sne*_*gan 3 iphone xcode image uiscrollview ios

基本上,我想要一个只有一个视图的应用程序,上面有一个图像.我希望能够向左或向右滑动,让第一张图像离开视图,第二张图像进入.图像是相同的,我希望它看起来像是连接起来的(比如向下滚动一根绳子模式只是重复,但它看起来像一个恒定的滚动).我需要它能够更改图像或在一系列滑动后重新启动.我知道我需要在UIScrollView中打开分页,但我是iOS的新手并且遇到了麻烦.

最终,我想让iPhone每次刷卡都会振动(并重新启动模式).

我确信有很多方法可以做到这一点(即TableView),所以如果答案很难解释,请随意指出一些参考方向.

谢谢!

跟进:

我找到了一个苹果的例子,它几乎完成了我想做的事情.我对它进行了很多调整,但是我正在撞墙试图让图像循环.以下是我认为有问题的代码,但我不确定解决方案是什么,因为ScrollView功能正常,它不会将中心重置为当前视图.有任何想法吗?

    - (void)layoutScrollImages
{
        UIImageView *view = nil;
        NSArray *subviews = [scrollView1 subviews];

    // reposition all image subviews in a horizontal serial fashion
    CGFloat curXLoc = 0;
    for (view in subviews)
    {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
            CGRect frame = view.frame;
            frame.origin = CGPointMake(curXLoc, 0);
            view.frame = frame;

            curXLoc += (kScrollObjWidth);
        }
    }

    // set the content size so it can be scrollable
    [scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];

}
Run Code Online (Sandbox Code Playgroud)

Aar*_*man 7

我只是使用UIScrollView.将contentWidth设置为视图宽度/高度的3倍(3页),并将contentOffset设置为中心"页面"(view.bounds.size.widthview.bounds.size.height取决于您是否分别水平/垂直滚动).您需要为UIScrollView(可能是视图控制器)设置委托并实施- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView.滚动视图完成减速时将调用此方法.完成减速后,将contentOffset重置回中心视图.这应该给人一种无限卷轴的印象.您还可以在scrollViewDidEndDecelerating方法中设置一个递增计数器,以递增计数器或启动振动.

您不应该继续重新定位图像.只需在scrollView中设置一次图像:

//Horizontal arrangement
UIImage *image = [UIImage imageNamed:@"nameOfImage.png"];
UIImageView *imageView1 = [[UIImageView alloc] initWithImage:image];
UIImageView *imageView2 = [[UIImageView alloc] initWithImage:image];
UIImageView *imageView3 = [[UIImageView alloc] initWithImage:image];
NSArray *imageViews = [NSArray arrayWithObjects:imageView1, imageView2, imageView3];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview: scrollView]; //This code assumes it's in a UIViewController
CGRect cRect = scrollView.bounds;
UIImageView *cView;
for (int i = 0; i < imageViews.count; i++){
    cView = [imageViews objectAtIndex:i];
    cView.frame = cRect;
    [scrollView addSubview:cView];
    cRect.origin.x += cRect.size.width;
}
scrollView.contentSize = CGSizeMake(cRect.origin.x, scrollView.bounds.size.height);
scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0); //should be the center page in a 3 page setup
Run Code Online (Sandbox Code Playgroud)

所以图像设置好了,你不需要再乱用了.只需在滚动视图停止时重置contentOffset(注意:您需要确保您是滚动视图的委托,否则当滚动视图停止时您将不会收到消息):

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0);
}
Run Code Online (Sandbox Code Playgroud)

请原谅任何错别字.我手工写出来了.

  • 您还可以添加scrollview.pagingEnabled = YES; 然后你不需要委托scrollviewDidEndDecelerating: (2认同)