2014-12-02 29 views
0

我正在研究一個應用程序,您可以在該應用程序中將不同的圖像從庫中添加到可拖動它們的視圖中,如果在圖像上按長應刪除它。新導入的圖像放置在CGRect中,然後應用drag和longpress的功能。

我的問題是從我的刪除代碼,刪除工作,但它只刪除最後插入的圖像。UIGestureRecognizer刪除應用了LongPress的特定UIImageView

self.myImageView = [[Draggable alloc]initWithFrame:cellRectangle]; 
[self.myImageView setImage:self.myImage]; 
[self.myImageView setUserInteractionEnabled:YES]; 
[self.myImageView setTranslatesAutoresizingMaskIntoConstraints:YES]; 
[self.myImageView setPreservesSuperviewLayoutMargins:YES]; 

[self.customCam addSubview:self.myImageView]; 

此代碼將可拖動的類分配給UIImageView,該UIImageView用於在屏幕上拖動圖像。下面是長按動作代碼:

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode:)]; 
    longPress.delegate = self; 
    longPress.minimumPressDuration = 1.0; 
    [self.myImageView addGestureRecognizer:longPress]; 

activateDeletionMode代碼如下

- (void)activateDeletionMode:(UILongPressGestureRecognizer *)sender 
{ 
     if (sender.state == UIGestureRecognizerStateBegan) 
     { 
      [self.myImageView removeFromSuperview]; 
      NSLog(@"This Runs"); 
     } 
} 

只有一個圖像插入它工作正常。但是,如果我同時插入2張圖像,則會刪除最新插入的圖像,並且不會在第二張圖像上執行removeFromSuperview

回答

0

您應該爲每個imageView添加一個新的longpress手勢。

+0

每次添加一個新的圖像視圖時,這一行'[self.myImageView addGestureRecognizer:longPress];'爲它添加一個新的longpress手勢。但是,如果添加了新的控件,則該控件將轉移到新的控件中。那麼我該怎麼做才能爲每個新的imageview生成新的longpress? – 2014-12-02 10:52:19

+0

如果您創建了幾個imageViews,您應該創建一個NSArray來包含imageViews。所以代碼是'imageViews中的imageView' {UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode :)]; [imageView addGestureRecognizer:longPress];}' – mengxiangjian 2014-12-02 10:57:58