【问题标题】:Why does a UIImageView move all crazy when touchesBegan starts at the UIImageView?当 touchesBegan 从 UIImageView 开始时,为什么 UIImageView 会疯狂移动?
【发布时间】:2012-10-08 13:07:51
【问题描述】:

所以我以编程方式创建了一个 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 在两个位置之间快速闪烁。

感谢阅读。

【问题讨论】:

    标签: objective-c xcode uiimageview touchesbegan touchesmoved


    【解决方案1】:

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

    编辑:

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

    【讨论】:

    • 我已经通过添加您的代码和修改来编辑我的答案。我希望这会起作用/有帮助。
    猜你喜欢
    • 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
    相关资源
    最近更新 更多