我开始使用Objective-C,关于变量范围的某些事情我仍然没有得到。我进行了搜索,但仍然无法捕捉到我做错了什么。

我正在尝试创建一个代码,该代码将给我两点之间的x,y差异。第一个IF中的第一个NSLog显示pointWhereDragBegan.x和.y的正确值,但是当我尝试在第二个IF语句中获取pointWhereDragBegan的值时,我获得的pointWhereDragBegan.x的值是-1.998683和.y是0.0。

我敢肯定这确实很简单,我只是无法抓住我的错误。

- (void)drag:(UILongPressGestureRecognizer *)drag{

CGPoint pointWhereDragBegan;
if(drag.state == UIGestureRecognizerStateBegan){
    pointWhereDragBegan = [drag locationInView:self];
    NSLog(@"Drag started at %f,%f",pointWhereDragBegan.x,pointWhereDragBegan.y);
}

if(drag.state == UIGestureRecognizerStateEnded){
    CGPoint pointWhereDragEnded = [drag locationInView:self];

    float xDragged = pointWhereDragEnded.x - pointWhereDragBegan.x;
    float yDragged = pointWhereDragEnded.y - pointWhereDragBegan.y;



    NSLog(@"Drag ended at %f,%f",pointWhereDragEnded.x,pointWhereDragEnded.y);
    NSLog(@"The user moved %f, %f",xDragged,yDragged);
}
}

最佳答案

drag.state永远不会同时成为UIGestureRecognizerStateBeganUIGestureRecognizerStateEnded。该方法应被调用两次:每个状态一次。

因此,为了解决您的问题,您需要将pointWhereDragBegan保留在方法范围之外。例如,您可以使用实例变量。

10-08 06:57