UILongPressGestureRecognizer

UILongPressGestureRecognizer

我有一个带有各种IBOutlet的自定义单元格,但是我想在一个按钮上添加一个UILongPressGestureRecognizer以进行长按手势。这是我的代码(btw插座连接正确,按钮的IBAction方法正确调用):

MyCustomCell.h

@interface MyCustomCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UIButton *myButton;
@property (strong, nonatomic) UILongPressGestureRecognizer *longPressGestureRecognizer;
@end

MyCustomCell.m

- (void)awakeFromNib
{
    // Initialization code
    self.longPressGestureRecognizer = nil;
}

MyViewController.m

#import MyCustomCell.h

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (!cell){
        cell = [[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }

    cell.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
    cell.longPressGestureRecognizer.minimumPressDuration = 1.0f;
    cell.longPressGestureRecognizer.allowableMovement = 300.0f;
    [cell.myButton addGestureRecognizer:cell.longPressGestureRecognizer];
}

- (void)handleLongPressGestures:(UIGestureRecognizer *)recognizer
{
    if ([recognizer.view isKindOfClass:[UIButton class]]){
        if (recognizer.state == UIGestureRecognizerStateBegan){
            NSLog(@"Long press began");
        } else if (recognizer.state = UIGestureRecognizerStateEnded){
            NSLog(@"Long press ended");
        }
    }
}

问题是从未调用handleLongPressGestures:方法。

最佳答案

longPressGestureRecognizer应该是控制器上的属性,而不是view(MyCustomCell)。将属性移到MyViewController,然后重试。我的猜测是,它在MyCustomCell排队和出队时发生了奇怪的事情。
要重用的对象(单元)应轻巧。在这种情况下,longPressGestureRecognizer的目标是视图控制器,并且很讨厌。

关于ios - 在自定义UITableViewCell内的UIButton中添加UILongPressGestureRecognizer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30626888/

10-09 10:01