在我的应用中,我有这个代码来拖动一个对象
我设定了手势:
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer new] initWithTarget:self action:@selector(dragGestureChanged:)];
downwardGesture.minimumPressDuration = 0.2;
[grid_element addGestureRecognizer:downwardGesture];
for (UILongPressGestureRecognizer *gestureRecognizer in self.view.gestureRecognizers)
{
[gestureRecognizer requireGestureRecognizerToFail:downwardGesture];
}
在我的方法中:
- (void) dragGestureChanged:(UILongPressGestureRecognizer*)gesture{
UIImageView *imageToMove;
CGPoint pointInSelfView;
if (gesture.state == UIGestureRecognizerStateBegan)
{
dragging = TRUE;
CGPoint location = [gesture locationInView:grid_element];
NSIndexPath *selectedIndexPath = [grid_element indexPathForItemAtPoint:location];
if (selectedIndexPath==nil) {
dragging = FALSE;
return;
}
indexToHide = selectedIndexPath.row;
imageToMove = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image_1.png"]];
[self.view addSubview:imageToMove];
pointInSelfView = [gesture locationInView:self.view];
[imageToMove setCenter:pointInSelfView];
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
pointInSelfView = [gesture locationInView:self.view];
[imageToMove setCenter:pointInSelfView];
}
else if (gesture.state == UIGestureRecognizerStateEnded ||
gesture.state == UIGestureRecognizerStateCancelled ||
gesture.state == UIGestureRecognizerStateFailed)
{
dragging = FALSE;
}
}
它在UIGestureRecognizerStateBegan
中工作,然后imageToMove
在self.view
中添加到正确的位置,但imageToMove
不会拖入UIGestureRecognizerStateChanged
;我在NSLog
中显示pointInSelfView
UIGestureRecognizerStateChanged
,并且更改正确;问题出在哪里?
修改
如果我使用imageToMove作为IBOutlet它工作正常,但我不明白其中的区别。
答案 0 :(得分:0)
如果您使用的是ARC,则iOS系统会释放对象 - imageToMove
使用retain属性创建属性会使系统保留对象,从而使其移动。
我唯一感到困惑的是[imageToMove setCenter:pointInSelfView];
中没有错误的原因。应该有一个错误说 - 消息被发送到解除分配的实例。但我很确定问题是由于imageToMove的内存释放造成的。