iOS UITableView单元格选择

3
我有一个UITableView,其中包含一个名为NewCell的自定义单元格。我试图在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。
非常奇怪,我似乎无法确定为什么会这样。
我一定是做错了什么。

这对我来说看起来很好。你能分享一下你的单元格创建代码吗? - mopsled
该死,我找到问题了。我实际上仍然将productCell.selectionStyle设置为表格。我移除了它,现在它可以工作了。但是如果保留它,会产生我在原帖中所描述的尴尬副作用。 - boostedz06
很高兴你已经解决了。对于未来的人,将你的解决方案作为答案并接受它。 - mopsled
谢谢,但是它说我必须等待2天才能做到这一点,也许你可以。我刚刚添加了它。 - boostedz06
1个回答

5
原因是因为您需要将选择样式设置为 none,像这样:

productCell.selectionStyle = UITableViewCellSelectionStyleNone;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接