如何到达didSelectRowAtIndexPath中的当前选定单元格?


67

我想通过方法来改变细胞的附属视图类型:didSelectRowAtIndexPath方法,即在选择行我想改变附属视图类型,我可以做这里面的那个方法?

Answers:


143

您可以像这样使用indexPathdidSelectRowAtIndexPath:方法获取单元格。

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

当我使用您的解决方案使[cell setAccessoryType:UITableViewCellAccessoryDe​​tailDisclosureButton]对其附件视图无效时,怎么了?
JaHelia

@JaHelia,您是否正在使用didSelectRowAtIndexPath:方法重新加载表视图[tableView reloadData]
EmptyStack

我认为您必须以某种方式保存索引路径,然后在cellForRowAtIndexPath中设置附件视图。否则,每次tableview向委托人询问单元格时都会覆盖它。
Tobi

@JaHelia,是的。你应该做的@Tobi如上所述,使细胞显示附属视图重新加载表视图即使经过
EmptyStack

您还可以在单​​元格上使用setNeedsLayout
卸妆

9

在Swift 3.0中:您可以根据需要使用这两种方式

 let cell:UITableViewCell = tableView.cellForRow(at: indexPath) as UITableViewCell

要么

let cell:CustomTableViewCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell

快乐编码!


5
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
     UITableViewCell *myCell = [tableView cellForRowAtIndexPath:indexPath];
     // Access accessory View  as below.  
     UIView * myCellAccessoryView = myCell.accessoryView;
}

3

使用下面的函数并传递所选行的索引路径,以便再次重新加载特定的单元格。

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

另一个解决方案:存储选定的行索引并重新加载tableview。然后cellForRowAtIndexPath检查所选行并更改单元格的附件视图。


3

迅速

您可以使用indexPath从didSelectRowAtIndexPath:方法获取单元格,如下所示:

 let cell:UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)

1

存储选定的索引路径。例如:NSInteger selectedIndexPath; 然后按照以下步骤操作。设置您的附件视图。

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    AddressTableViewCell *cell=(AddressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    cell.backgroundColor=[UIColor lightGrayColor];

    Address *addr=[self.locationArray objectAtIndex:indexPath.row];

    cell.titleLabel.text = addr.addressTitle;
    cell.detailLabel.text = addr.addressDetail;

        if (indexPath.row == selectedIndexPath) {
            [cell.selectButton setImage:[UIImage imageNamed:@"checkboxFilled"] forState:UIControlStateNormal];
        }
        else {
            [cell.selectButton setImage:[UIImage imageNamed:@"checkbox"] forState:UIControlStateNormal];

        }

    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    selectedIndexPath=indexPath.row;

    [self.tableView reloadData];

}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.