2014-10-22 46 views
0

我有DragView對象和DropView對象,它們都是UIView子類,在UIView容器中。在手勢平移上調用以下selector方法。問題是,當我將DragView對象拖到DropView對象上時,DragView對象就會消失。我不知道我做錯了什麼。當addsubview:被調用時,UIView拖放 - 拖動視圖消失?

- (void)dragViewMoved:(UIPanGestureRecognizer *)gesture{ 

    CGPoint touchLocation = [gesture locationInView:self]; 

    static DragView *currentDragView; 
    static DropView *currentDropView; 

    if(UIGestureRecognizerStateBegan == gesture.state){ 

     for(DragView *dragView in self.dragViews){ 

      if(CGRectContainsPoint(dragView.frame, touchLocation)){ 
       currentDragView = dragView; 
       break; 
      } 
     } 

    }else if(UIGestureRecognizerStateChanged == gesture.state){ 

     currentDragView.center = touchLocation; 

     for(DropView *dropView in self.dropViews){ 

      if(CGRectIntersectsRect(currentDragView.frame, dropView.frame)) 
       currentDropView = dropView; 

     } 

    }else if (UIGestureRecognizerStateEnded == gesture.state){ 

     if(CGRectIntersectsRect(currentDragView.frame, currentDropView.frame)){ 

      //I think the problem is happening here 
      currentDragView.center = touchLocation; 
      [currentDragView removeFromSuperview]; 
      [currentDropView addSubview:currentDragView]; 

     } 

     currentDragView = nil; 

    } 

} 

enter image description here

+0

爲什麼你'currentDragView'和'currentDropView'是'static'? – gran33 2014-10-22 06:43:49

+0

還有誰(強引用)'currentDragView'? – gran33 2014-10-22 06:45:00

+0

@ gran33它們是「靜態」的,因此當用戶拖拽「DragView」時,它們在手勢選擇器調用之間保持不變。在'.xib'文件中初始化的父視圖擁有對'currentDragView'的強引用。 – Michael 2014-10-22 06:49:59

回答

1

而不是做這個的:

currentDragView.center = touchLocation; 

試圖改變這樣的:

currentDragView.center = [gesture translationInView:currentDropView]; 

更新:

嘗試切換此行:

static DragView *currentDragView; 

要這樣:

DragView *currentDragView = gesture.view; 
+0

試過,它沒有工作。當我在'currentDropView'上調用'addSubview:'時'currentDragView'被添加到'currentDropView'的'subviews'屬性,它不會出現... – Michael 2014-10-22 07:36:01

+0

它解決了你的問題嗎? – gran33 2014-10-23 06:29:52

+0

不,'currentDragView'是其中'currentDragView'和'currentDropView'是兄弟的容器的'subview'。 – Michael 2014-10-23 06:38:58