ios - 检测 UITableViewCell 是否为重用单元格

标签 ios objective-c uitableview

在我的应用程序中,我有带有多个按钮的 UITableView 单元格。每个单元格 4 个 UIButton。对于每个 UIButton,我想添加一个 UILongPressGestureRecognizer。下面的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    FriendViewCell *cell = (FriendViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


    for(int i =0; i<4; i++) {




            UIButton *button = cell.buttons[i];
            UILabel *label = cell.labels[i];

            [button setTag:(int)indexPath.row*4+i];
            [button addTarget:self action:@selector(friendTapped:) forControlEvents:UIControlEventTouchUpInside];

            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressFriend:)];

            [button addGestureRecognizer:longPress];

}

}

我刚刚意识到,如果重复使用一个单元格,那么我会在每个按钮上多次添加一个手势。有没有办法检测创建的​​单元格是重复使用的还是新的?我不认为我可以将代码移动到 FriendViewCell 类,因为我的手势目标friendTapped:在我的 UITableViewController 中。任何指针将不胜感激!谢谢

最佳答案

更简洁的方法是为您的 Button 创建一个自定义类。 .此类将有 UILongPressGestureRecognizer在初始化时创建,并在触发手势时调用委托(delegate)(您的 Controller )。

.h

@class MyLongPressedButton
@protocol MyLongPressedButtonDelegate
- (void)buttonIsLongPressed:(MyLongPressedButton *)button;
@end

@interface MyLongPressedButton
@property (nonatomic, weak) id<MyLongPressedButtonDelegate > delegate
@end

.m
-(id)init {
   if (self = [super init]) {
     UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
     [self addGestureRecognizer:longPress];

   }
   return self;
}

-(void)longPress:(id)sender {
   [_delegate buttonIsLongPressed:self]
}

关于ios - 检测 UITableViewCell 是否为重用单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28586342/

相关文章:

iOS10 语音识别器拼写

ios - 如何从我自己的 native 应用程序中启动 Google Maps iPhone 应用程序?

iphone - UITableView 奇怪的行为

swift - 更新核心数据对象顺序 - 不工作

swift - 检测何时从单元格本身中选择自定义单元格?

ios - 在 Swift 中访问 NSManagedObject 属性

ios - 神秘的 UIButton 崩溃

ios - isDataAvailable 导致 warnParseOperationOnMainThread() Parse.com

ios - XCode 不断撤销我所有的配置文件

ios - Obj-C createFileAtPath 问题 - 永远不会创建文件?