当touchesBegan从UIImageView开始时,为什么UIImageView会变得疯狂?

时间:2012-10-08 13:07:51

标签: objective-c xcode uiimageview touchesbegan touchesmoved

所以我以编程方式创建了一个UIImageView,并将它放在一个数组上。在touchesMoved中,我将UIImageView的x位置设置为触摸的x位置。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UIImageView *b in _blocks) {
    if ( b.image != wall) {
        movingimage = b;
        movingimage.userInteractionEnabled = YES;

        NSLog(@"touch");
     }
 }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint location = [touch locationInView:touch.view];
CGPoint xlocation = CGPointMake(location.x, movingimage.center.y);
movingimage.center = xlocation;
}

如果不是使用以编程方式创建的UIImageView,而是使用在Interface Builder中创建的UIImageView,则此代码可以正常工作。但是当我使用代码创建UIImageView并且tochesBegan从UIImageView开始时,touchesMoved的触摸坐标变得疯狂,而imageView在两个地方之间闪烁得非常快。

感谢阅读。

1 个答案:

答案 0 :(得分:2)

我想这是因为你从一个视图中获得接触点,然后你正在重新定位。所以下一个事件将是“不正确的”。我认为你能做的最好的事情就是从超级视图中捕捉触摸位置。

编辑:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches]anyObject];
    CGPoint location = [touch locationInView:[movingimage superview]];
    CGPoint xlocation = CGPointMake(location.x, movingimage.center.y);
    movingimage.center = xlocation;
}