ios - UITableViewCell 中的 TapGesture 导致其他单元格状态改变

标签 ios objective-c iphone uitableview

我正在制作我的第一个 iOS 应用程序,我有一个带有 UITableViewCells 列表的 UITableView。每个 UITableViewCells 都有两个标签:

@property (weak, nonatomic) IBOutlet UILabel *upvote;
@property (weak, nonatomic) IBOutlet UILabel *downvote;

这些标签每个都有一个手势识别器。当点击标签时,两个标签的 alpha 都通过动画设置为 0。

-(void) handleSingleTapGesture: (UITapGestureRecognizer *)gestureRecognizer
{
    UILabel *vote = (UILabel*)[gestureRecognizer view];
    AppCell *appCell = (AppCell*)vote.superview.superview;

    [UIView animateWithDuration: 1.0 animations:^(void) 
    {
        appCell.upvote.alpha = 0;
        appCell.downvote.alpha = 0;
    }
}

这是 cellForRawAtIndexPath 方法:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath 
{
    AppCell *cell = (AppCell *)[tableView dequeueReusableCellWithIdentifier:@"AppCell"];
    App *app (self.apps)[indexPath.row];

    /** setting the text/fonts/alpha for other labels I get from a HTTP POST request. Did not include the code since not relevant */

    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];

    cell.upvote.font = [UIFont fontWithName:@"Roboto-Light" size:14];
    [cell.upvote setUserInteractionEnabled:YES];
    [cell.upvote addGestureRecognizer:singleTapGestureRecognizer];

    *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];

    cell.downvote.font = [UIFont fontWithName:@"Roboto-Light" size:14];
    [cell.downvote setUserInteractionEnabled:YES];
    [cell.downvote addGestureRecognizer:singleTapGestureRecognizer];

}

它正常工作。当我点击文本时,它们都消失了。但是,当我向下滚动时,一些 future 的单元格似乎没有 UPVOTE/DOWNVOTE 文本。

我非常有信心它与细胞的重用有关,但我不知道如何修复它。

我已经查找了可能的解决方案,但似乎找不到太多。我唯一能找到的是将手势识别器添加到 UITableView 而不是 UITableViewCell 更有效。我不能这样做,因为我不希望在点击单元格时发生操作,只有在点击两个标签之一时才会发生。

如果需要更多信息/有我在 StackOverflow 上遗漏的解决方案,请告诉我。

最佳答案

正如您所猜测的,这可能与单元格的重用有关。 cellForRowAtIndexPath 方法中的注释说它处理 alpha,但该方法中没有设置 alpha,所以...

当单元格被重用时,upvotedownvote 标签 alpha 是它最后设置的值,无论是隐式的(当 UILabel 创建)或显式(由手势处理程序设置为 0)。

您需要跟踪每个单元格的投票,并在 cellForRowAtIndexPath 方法中适当设置 alpha。

关于ios - UITableViewCell 中的 TapGesture 导致其他单元格状态改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338838/

相关文章:

ios - ReactiveCocoa - 从未调用过的 flattenMap block

iphone - 隐藏有关缺少体系结构信息的 Xcode dsymutil 警告

javascript - 如何将 touchstart 事件正确转换为 mousedown?

ios - BundlePath 为零,但 NSLog 打印正确的路径

ios - 我得到这个 “Thread 1: signal SIGABRT”

ios - RNDecryptor addData 方法中的混淆

iphone - 有 WatchKit 传感器 API 吗?

iphone - 在 UIWebview 上编辑文本字段时关闭键盘

ios - 自定义 UINavigationController UIToolbar 子类

iOS Today 小部件在底部被截断