iOS UITableView 单元格选择

标签 ios uitableview

我有一个带有名为 NewCell 的自定义单元格的 UITableView,我试图在点击事件时在 NewCell 中显示一个名为“selectedView”的 UIView。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewCell *cell = (NewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell.selectedView setHidden:NO];
}

编辑 - 添加单元格创建代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NewCell";
    NewCell *productCell = (NewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (productCell == nil) 
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"NewCell" owner:nil options:nil];

        for (id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[UITableViewCell class]])
            {
                productCell = (NewCell *) currentObject;
                break;
            }
        }
    }

    Product *mainProduct = [self.productsArray objectAtIndex:indexPath.row];

    float floatPrice = [mainProduct.price floatValue];
    NSString *priceFormat;
    if ((int)floatPrice == floatPrice) priceFormat = @"$%.0f"; else priceFormat = @"$%.2f";

    produtCell.productPrice.text = [NSString stringWithFormat:priceFormat, floatPrice];

    return productCell;
}

一切正常,表格会填充,但是当我选择一个单元格时,它不会在表格中选择的单元格上显示 selectedView,而是在相反的单元格中显示 selectedView。 我的意思是,如果屏幕上显示第 0 行和第 1 行并且我选择第 1 行,它将在第 0 行显示 selectedView,如果我选择第 0 行,它将在第 1 行显示 selectedView。

很奇怪,我似乎无法说出它为什么这样做。

我一定是做错了什么。

最佳答案

这样做的原因是因为您需要将选择样式设置为无,如下所示:

productCell.selectionStyle = UITableViewCellSelectionStyleNone;

关于iOS UITableView 单元格选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11435753/

相关文章:

ios - 在 iOS 上编译 Phonegap 项目

ios - UITableViewCell 在 subview 性能问题中调用 .layer.maskToBounds = YES

ios - Swift 中来自 nib 的自定义 UITableViewCell

ios - 无法将内容添加到 IB 中 View Controller 中的自定义表格 View 单元格

c++ - 找不到架构 i386 的符号 - 但适用于 iOS 设备

ios - 像 uber 一样在 Mapbox map 上移动 MGLPointAnnotation

ios - 如何在 MKMapview 上跟踪用户位置并在用户路径上画线

ios - 在加载 UITableVIew 之前从解析中检索图像?

ios - UITableViewCell 何时何地完成布局?

ios - 如何做文本字段抖动效果?