【问题标题】:Detect selected UIImageView检测选定的 UIImageView
【发布时间】:2013-05-24 08:59:48
【问题描述】:

如何确定当前在视图中触摸了哪个UIImageView? UIImageViews 是动态创建的,并且基于标签。我还将使用带有我的对象和数组索引的标签以供参考。我已经读到我需要在这种情况下使用UIButton,但UIButton 的问题是我不能将它拖到自己的范围之外。

我需要知道如何通过标记获取特定的动态创建的按钮,以便我可以检测到哪个UIImageView 在TouchesMoved 中移动。

这是从我的对象创建UIImageViews 的代码:

for (ObjectClass *obj in [self myDelegate].theObj)
{
    CGRect rect = CGRectMake(obj._sX + (obj._sW / 2),obj._sY + (obj._sH / 2),10,10);
    handlerImg = [[UIImageView alloc] initWithFrame:rect];
    handlerImg.backgroundColor = [UIColor yellowColor];
    [[self view] addSubview:handlerImg];
    handlerImg.tag = z;
    [handlerImg setUserInteractionEnabled:YES];
    z++;
}

然后是 touchesMoved 事件的代码:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (drag == YES)
    {
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInView:self.view];
        ObjectClass *obj = [[self myDelegate].theObj objectAtIndex:currHandler]; //Get object based on selected UIImageView

        if ([touch view] == handlerImg) //Identify which UIImageView is selected
        {
            someImage.center=location;

【问题讨论】:

  • 当您使用标签时,为什么您无法获取图像视图
  • 因为我只得到最后一个标签的 UIImageView。
  • 那么你想要哪个标签是最新的还是以前的
  • jeraldov,您可以尝试在 for 循环中创建本地 UIImageView 而不是使用 handlerImg 吗?我认为您每次都在 for 循环中覆盖 handlerImg UIImageView ,也许这就是为什么标签值始终是 for 循环的最后一个值的原因。看看有没有帮助。
  • @AshutoshMishra 我实际上想要选定的标签或正在点击的 UIImageView。

标签: ios xcode uiimageview uitouch


【解决方案1】:

这样试试

if ([[touch view] isKindOfClass:[UIImageView class]]) //Identify which UIImageView is selected
        {
            someImage.center=location;
            //[touch view].tag here you'l get tag value.

        }

(或)

使用手势,在 .h 文件中添加手势委托并将其放在 ein for 循环中。

UITapGestureRecognizer *tapRecognizer;
    tapRecognizer=[[UITapGestureRecognizer alloc] 
                   initWithTarget:self
                   action:@selector(handleTap:)];
    tapRecognizer.numberOfTapsRequired=1;
    tapRecognizer.numberOfTouchesRequired=1;
    [imageview addGestureRecognizer:tapRecognizer];
    tapRecognizer.delegate = self;
    [tapRecognizer release];

然后放这个

- (void)handleTap:(UITapGestureRecognizer *)recognizer {

    NSLog(@"KidsViewController ==> handleTap.");

    switch (((UIGestureRecognizer *)recognizer).view.tag)      
    {
         //do whatever you want here
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多