2012-06-19 37 views
0

我有一个UIView,带有子视图(lastView)的UISCrollView的子视图。我想要的是当我长时间按下视图时,它将删除lastView。然后再次长按lastView将再次出现。我试过了,但我只有这么远。我的lastView没有出现,我的long press gesture也没有工作。长按手势和子视图不工作

这里是我的代码:

- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { 
    if (sender.state == UIGestureRecognizerStateEnded) { 
     [self.slotView removeFromSuperview]; 
     NSLog(@"Long press Ended"); 
    } 
    else { 
     NSLog(@"Long press detected."); 
    } 
} 

- (void) createScrollView { 
    self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)]; 
    CAGradientLayer *gradient = [CAGradientLayer layer]; 
    gradient.frame = self.slotBg.bounds; 
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil]; 
    [self.slotBg.layer insertSublayer:gradient atIndex:0]; 
    [self.view addSubview:self.slotBg]; 
    UILongPressGestureRecognizer *longPress = 
    [[UILongPressGestureRecognizer alloc] initWithTarget:self 
              action:@selector(handleLongPress:)]; 
    longPress.minimumPressDuration = 2.0; 
    [slotBg addGestureRecognizer:longPress]; 

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)]; 
    [slotBg addSubview:scrollView]; 

    self.slotView = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)]; 
    [scrollView addSubview:slotView]; 

    int row = 0; 
    int column = 0; 
    for(int i = 0; i < _thumbs.count; ++i) { 

     UIImage *thumb = [_thumbs objectAtIndex:i]; 
     UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     button.frame = CGRectMake(column*60+10, row*60+10, 60, 60); 
     [button setImage:thumb forState:UIControlStateNormal]; 
     [button addTarget:self 
        action:@selector(buttonClicked:) 
     forControlEvents:UIControlEventTouchUpInside]; 
     button.tag = i; 

     [scrollView addSubview:button]; 

     if (column == 4) { 
      column = 0; 
      row++; 
     } else { 
      column++; 
     } 

    } 

    [scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)]; 
} 

回答

0

在视图的touchesBegan:你可以打电话给你的“长按”处理一些延迟。

[touchHandler performSelector:@selector(longTap:) withObject:nil afterDelay:1.5]; 

然后在视图的touchesEnded:如果没有足够的时间已经过去了,你可以取消呼叫:

[NSObject cancelPreviousPerformRequestsWithTarget:touchHandler selector:@selector(longTap:) object:nil]; 

添加BOOL *标志在视.h文件中;并在viewDid载入中加入flag = true;

现在选择longTap:应该是:

-(void)longTap:(id)sender 
{ 
    if(flag){ 
    flag = false; 
    [lastView removeFromSuperView]; 
    } 
    else{ 
    flag = true; 
    //Create lastView reference 
    [scrollView addSubView:lastView]; 
    } 
} 
0

添加UIGestureRecognizerDelegate谱写- (void) createScrollView[longPress setDelegate:self];。我认为这对你有帮助。