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

时间:2012-02-25 01:53:54

标签: iphone ios xcode image uiscrollview

基本上,我想要一个只有一个视图的应用程序,上面有图像。我希望能够向左或向右滑动,让第一张图像离开视图,第二张图像进入。图像是相同的,我希望它看起来像是连接起来的(比如向下滚动一根绳子模式只是重复,但它看起来像一个恒定的滚动)。我需要它能够更改图像或在一系列滑动后重新启动。我知道我需要在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)];

}

2 个答案:

答案 0 :(得分: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

因此设置了图像,您不再需要弄乱它们了。只需在滚动视图停止时重置contentOffset(注意:您需要确保您是滚动视图的委托,否则当滚动视图停止时您将不会收到消息):

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

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

答案 1 :(得分:1)

cocoacontrols.com上查看自定义相册视图。至于振动,此代码段会震动手机(确保链接到#import <AudioToolbox/AudioToolbox.h>):

 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);