iOS触及开放问题

时间:2012-07-27 21:01:04

标签: ios touchesbegan touchesmoved

我有一个NSArray whit 15 UIImageViews:

@interface ViewController : UIViewController{

    NSArray *ArrayImages1;
    NSArray *ArrayImages2;

}

在viewDidLoad中:

 ArrayImages1 = [[NSArray alloc] initWithObjects: a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, nil];

其中a1,a2 ......是UIImageViews的出口 对于ArrayImages2也是如此

TouchesBegan和TouchesMoved:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    UIImageView *posible;
    int imagen;
    if (point.x < 161) {
        imagen = Contador1;
        if (Contador1 > 14) {imagen = Contador1 - 15;}
        imagen--;
        posible = [ArrayImages1 objectAtIndex:imagen];
    }
    else if (point.x > 159) {
        imagen = Contador2;
        if (Contador2 > 14) {imagen = Contador2 - 15;}
        imagen--;
        posible = [ArrayImages2 objectAtIndex:imagen];
    }
    if ([touch view] != posible) { return; }
    original2 = posible.center;    
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    UIImageView *posible;
    int imagen;
    if (point.x < 161) {
        imagen = Contador1;
        if (Contador1 > 14) {imagen = Contador1 - 15;}
        imagen--;
        posible = [ArrayImages1 objectAtIndex:imagen];
    }
    else if (point.x > 159) {
        imagen = Contador2;
        if (Contador2 > 14) {imagen = Contador2 - 15;}
        imagen--;
        posible = [ArrayImages2 objectAtIndex:imagen];
    }
    if ([touch view] != posible) { return; }
    posible.center = point;
}

我必须知道触摸是否在两个可能的UIImageViews之一中,如果是,请移动它。 Contador1和Contador2整数是计数可以看到多少UIImageView的计数器,用户只能移动最后两个。

它有效,就是当我触摸外面时,它会让应用程序崩溃。 如果我更改touchesBegan和TouchesMoved,索引“posible = [ArrayImage ..”,对于0,它只适用于第一个UIImageView(我理解为什么),但它会崩溃。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

  

我必须知道触摸是否在两个可能的UIImageViews之一

我无法很好地遵循您的代码,但如果您首先检查该点是否在视图的矩形内,您似乎可以简化操作。然后根据结果建立逻辑。像

这样的东西

使用CGRectContainsPoint

bool CGRectContainsPoint (
   CGRect rect,
   CGPoint point
);



UIImageView *foundView

for(UIImageView* theView in ArrayImages1){

 if (CGRectContainsPoint(theView.frame, touchPoint){
     foundView = theView;
     break;
 }

}

则...

if (foundView != nil){
// do some logical thing

}

或者...

if ([foundView isEqual:someOtherView]){
// I may have the syntax wrong on the above

}