屏幕上有一張圖片需要在停留的時候全屏。
UILongPressGestureRecognizer *hold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(hold:)];
hold.minimumPressDuration = 0;
[self.photoImageView addGestureRecognizer:hold];
監聽器:
-(void)hold:(UILongPressGestureRecognizer *)sender{
UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
img.userInteractionEnabled = NO;
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"state began");
[self.view addSubview:img];
} else if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"state ended");
[img removeFromSuperview];
}
}
圖片成功添加到屏幕中,只有 [img removeFromSuperview]好像沒有響應。
結束狀態的NSlog也正常。
-(void)hold:(UILongPressGestureRecognizer *)sender{
//每次響應函數 img都是一個新alloc出來的UIImageView
UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
img.userInteractionEnabled = NO;
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"state began");
//添加新alloc出來的UIImageView,可以看到界面效果
[self.view addSubview:img];
} else if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"state ended");
//remove 新alloc出來的UIImageView當然沒有效果,它還沒有被add進去
[img removeFromSuperview];
}
}
改成這樣
-(void)hold:(UILongPressGestureRecognizer *)sender{
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"state began");
UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
img.userInteractionEnabled = NO;
img.tag = kTAG_PHOTO_IMAGE_VIEW
[self.view addSubview:img];
} else if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"state ended");
UIImageView *img = (UIImageView *)[self.view viewWithTag:kTAG_PHOTO_IMAGE_VIEW];
[img removeFromSuperview];
}
}