【问题标题】:TapGesture in UITableViewCell causing other cells to have altered stateUITableViewCell 中的 TapGesture 导致其他单元格的状态发生变化
【发布时间】:2014-12-07 02:14:11
【问题描述】:

我正在制作我的第一个 iOS 应用程序,并且我有一个 UITableView 和一个 UITableViewCells 列表。每个 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];

}

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

我很确定这与细胞的重复使用有关,但我不知道如何解决。

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

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

【问题讨论】:

  • 您也可以发布您的 cellForRowAtIndexPath 代码吗?

标签: ios objective-c iphone uitableview


【解决方案1】:

如您所料,这可能与细胞的重复使用有关。 cellForRowAtIndexPath 方法中的注释说它处理 alpha 但方法中没有设置 alpha,所以...

当一个单元格被重用时,upvotedownvote 标签的 alpha 是它最后设置的任何值,无论是隐式的(在创建 UILabel 时默认为 1)或显式(通过手势设置为 0)处理程序)。

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

【讨论】:

  • 我的意思是它处理阿尔法(通过设置初始阿尔法)。对困惑感到抱歉。这是否意味着它应该有诸如if (voted) app.upvote.alpha = 0; else app.upvote.alpha = 1;之类的东西?
  • @WilliamBingHua - 是的,这样的东西应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2020-08-31
相关资源
最近更新 更多