【问题标题】:Do something to selected image in scroll view在滚动视图中对选定图像执行某些操作
【发布时间】:2010-12-01 11:47:25
【问题描述】:

我尝试制作以下内容:图像的水平列表,我可以选择并使用它做一些事情。例如围绕 x 轴翻转图像。我知道如何旋转图像。我创建了滚动视图并用图像加载它。当我点击图像时,我添加了事件处理程序。但我不知道如何用点击的图像做一些事情。如何编写方法来对点击的图像进行操作?

- (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???   
}

【问题讨论】:

  • 您的代码中有一些内存泄漏。你必须释放那些你创建的 UIImageViews 和 UITapGestureRecognizers。
  • 1110,我像您一样添加了手势识别器,但无法调用 imageTapped 事件处理程序。您是否必须更新上面的代码才能使其正常工作?谢谢

标签: iphone objective-c uiscrollview uiimageview uiimage


【解决方案1】:

手势识别器有一个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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2023-03-03
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多