iOS UITableView单元格选择

boo*_*z06 3 uitableview ios

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

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

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

- (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;
}
Run Code Online (Sandbox Code Playgroud)

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

很奇怪,我似乎无法告诉它为什么这样做.

我一定做错了什么.

boo*_*z06 5

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

productCell.selectionStyle = UITableViewCellSelectionStyleNone;
Run Code Online (Sandbox Code Playgroud)