我開始使用Objective-C,並且還有一些關於變量範圍的問題,我仍然沒有得到。我搜索了它,但我仍然無法捕捉到我做錯了什麼。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);
}
}
您在第二個if語句中沒有記錄'pointWhereDragBegan'。你只記錄'pointWhereDragEnded'和減法的結果。 – 2012-04-22 21:08:50
我的意思是,在這種情況下,我記錄pointWhereDragBegin在第二個如果,值將是-1.998683和0. – rantunes 2012-04-22 21:13:22