相对于触摸移动 UIView [英] Move UIView with relation to touch

查看:31
本文介绍了相对于触摸移动 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试移动与用户触摸相关的 UIView.

i'm trying to move a UIView with relation to the user's touches.

这是我目前所拥有的:

int oldX, oldY;
BOOL dragging;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation)) {
        dragging = YES;
        oldX = touchLocation.x;
        oldY = touchLocation.y;
    }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation) && dragging) {
        CGRect frame;
        frame.origin.x = (window.frame.origin.x + touchLocation.x - oldX);
        frame.origin.y = (window.frame.origin.y + touchLocation.y - oldY);
        window.frame = frame;

    }

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    dragging = NO;
}

视图不断从一个位置闪烁到另一个位置,我不知道还能做什么.

The view keeps flickering from one location to another, and I don't know what else to do.

感谢任何帮助.

推荐答案

touchesBegantouchesMoved 方法修改为如下所示.

Modify the touchesBegan and touchesMoved methods to be like the following.

float oldX, oldY;
BOOL dragging;

touchesBegan:withEvent: 方法.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation)) {

        dragging = YES;
        oldX = touchLocation.x;
        oldY = touchLocation.y;
    }
}

touchesMoved:withEvent: 方法.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (dragging) {

        CGRect frame = window.frame;
        frame.origin.x = window.frame.origin.x + touchLocation.x - oldX;
        frame.origin.y =  window.frame.origin.y + touchLocation.y - oldY;
        window.frame = frame;
    }
}

touchesEnded:withEvent: 方法.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    dragging = NO;
}

这篇关于相对于触摸移动 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆