沿x轴和y轴移动UIImage



我创建了一个带有旋钮的控件。此旋钮只能沿x轴和y轴移动
我已经实现了以下方法:

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

我知道,限制沿一个轴的移动必须在touchMoved中实现。当我限制沿着例如x轴的移动时,一切都按预期进行。但是,如何实现y轴的运动呢?当我启用第二个轴时,旋钮的移动不会仅限于这两个轴。这里是touchMoved实现的一部分:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint currentLocation = [touch locationInView:self.view];
    CGPoint centerPoint = _triggerCap.center;
    CGPoint selectionTriggerCenter = _selectionTrigger.center;

    double distance = ({double d1 = centerPoint.x - selectionTriggerCenter.x, d2 = centerPoint.y - selectionTriggerCenter.y; sqrt(d1 * d1 + d2 * d2); });
    if (distance < 100.0) {
        if (fabsf(selectionTriggerCenter.y - currentLocation.y) > 5) {
            centerPoint.y = currentLocation.y;
            _triggerCap.center = centerPoint;

有人能给我一个提示吗?如何沿着两个移动?

我能想到的最快的方法是:

touchesBegan中,记录旋钮内第一次触摸的位置。然后,在touchesMoved中,等待,直到距离第一次触摸至少某个最小距离(可能是15个像素-四处播放,看看什么最有效)的触摸发生。检查它在x方向上还是在y方向上离第一次触摸更远。这将决定在当前触摸序列的剩余部分中应限制哪一个轴的移动。设置一个标志来指示轴,然后使用您已经拥有的代码将移动限制在单个轴上。重置touchesEnded中的标志,或者当旋钮返回到距离轴交点一定距离内时。

最新更新