5

我有一个UIViewController其中一个UIImageView和一个数组UIImage。如何开发向右或向左滑动功能以将图像更改为下一个数组位置?

4

3 回答 3

8

常见的方法是一个 UIScrollView 大小的图像之一,并启用分页。

将图像添加为子视图并像这样设置内容大小......

NSArray *images;
CGSize imageSize;

self.scrollView.frame = CGRectMake(10,10,imageSize.width,imageSize.height);
self.scrollView.contentSize = CGSizeMake(imageSize.width * images.count, imageSize.height);
self.scrollView.pagingEnabled = YES;

CGFloat xPos = 0.0;

for (UIImage *image in images) {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.width);
    [self.scrollView addSubview:imageView];
    xPos += imageSize.width;
    // assuming ARC, otherwise release imageView
}

您还可以关闭反弹、滚动指示器等,具体取决于您想要的效果的详细信息。

于 2012-05-06T01:46:31.987 回答
2

通过使用 UIScrollView 和 UIPageControl,拖放 UIScrollView 和 UIPageControl 确保它们不重叠,创建两者的 IBoutLet。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 1
imageArray = [NSArray arrayWithObjects:
                     [UIImage imageNamed:@"image2.jpg"],
                     [UIImage imageNamed:@"man-actor-Ashton-Kutcher-Wallpaper.jpg"],
                     [UIImage imageNamed:@"image1.jpg"],
                     [UIImage imageNamed:@"man-curl.jpg"],
                     [UIImage imageNamed:@"man-in-suit.jpg"],
                     nil];


  for (int i = 0; i < imageArray.count; i++) {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIImageView *subview = [[UIImageView alloc] initWithFrame:frame];
    subview.image = [imageArray objectAtIndex:i];
    subview.contentMode = UIViewContentModeScaleAspectFit;
    [self.scrollView addSubview:subview];
  }

  self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * imageArray.count, self.scrollView.frame.size.height);
  pageControl.numberOfPages = imageArray.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
  CGFloat pageWidth = self.scrollView.frame.size.width;
  int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
  self.pageControl.currentPage = page;
}
于 2015-03-09T12:19:04.163 回答
1

UISwipeGestureRecognizer您可以像这样简单地向左或向右滑动方向

swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe:)];
[swipeGesture setNumberOfTouchesRequired:1];
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp];
[appView addGestureRecognizer:swipeGesture];

该方法detectSwipe声明用于处理您的前进和后退以使用 UIImage 数组。您还可以查看Apple 的 SimpleGestureRecognizers 演示

希望对你有帮助!

于 2012-05-06T01:26:58.420 回答