在滚动视图中对所选图像执行某些操作

时间:2010-12-01 11:47:25

标签: iphone objective-c uiscrollview uiimageview uiimage

我尝试制作以下内容:水平的图像列表,我可以选择并使用它做一些事情。例如,围绕x轴的翻转图像。我知道如何旋转图像。我创建了scrollview并用图像加载它。我点击图片时添加了事件处理程序。但我不知道如何用拍摄的图像做些什么。如何编码方法用点击图像做某事?

- (void)viewDidLoad {
    [super viewDidLoad];        

    img1 = [UIImage imageNamed:@"imgTest.jpg"];
    img2 = [UIImage imageNamed:@"imgTest2.jpg"];

    arrayOfImages = [[NSMutableArray alloc] init];
    [arrayOfImages addObject:img1];
    [arrayOfImages addObject:img2];
    [arrayOfImages addObject:img1];
    [arrayOfImages addObject:img2];

    scrollView = [[UIScrollView alloc] init];
    scrollView.scrollEnabled = YES;
    scrollView.pagingEnabled = YES;
    scrollView.directionalLockEnabled = YES;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.backgroundColor = [UIColor blueColor];
    scrollView.autoresizesSubviews = YES;
    scrollView.frame = CGRectMake(0, 0, 320, 128);
    [self.view addSubview:scrollView];

    UIImage *imageToAdd;
    int x = 0;
    int y = 0;
    for(imageToAdd in arrayOfImages)
    {
        UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];     

        temp.frame = CGRectMake(x, y, 128, 128);
        temp.userInteractionEnabled = YES;      
        x += 135;


        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
        [temp addGestureRecognizer:tap];    

        [scrollView addSubview:temp];
    }
...

- (void)imageTapped:(UIGestureRecognizer *)sender
{

    // how to get reference on selected item in scrollview???   
}

1 个答案:

答案 0 :(得分:4)

手势识别器具有view属性,可返回与识别器关联的视图。既然你知道它将是一个UIImageView,你可以简单地投射它并在下面使用它:

UIImageView *iv = (UIImageView *)[sender view];

然后可以通过以下方式查询您的图像:

UIImage *image = [iv image];

如果您需要知道数组中的索引,有两种方法:只需使用[arrayOfImages indexOfObject:image];,或者您可以为视图分配标记(数字)并使用它们。 Apple没有使用标签,只有这样我们开发人员才能以某种方式“标记”视图。例如:

NSInteger counter = 0;
for(imageToAdd in arrayOfImages)
{
    UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
    count.tag = counter++;
    ...
}

然后,在imageTapped:中,您可以通过tag查询索引:

NSInteger index = [imageView tag];