如何显示自定义UITableViewCellAccessoryCheckmark

han*_*Dev 2 iphone objective-c uitableview ios

我有一个表视图,需要一个自定义UITableViewCellAccessoryCheckmark.选中行时会显示复选标记,选择另一行时会显示复选标记,然后显示在最后选择的最后一个视图上.这很好.

当我使用这一行时出现问题:

 cell.accessoryView = [[ UIImageView alloc ]
                            initWithImage:[UIImage imageNamed:@"icon-tick.png" ]];
Run Code Online (Sandbox Code Playgroud)

添加自定义UITableViewCellAccessoryCheckmark.在该代码之后,UITableViewCellAccessoryCheckmark保留在所有行上,并且在触摸另一行时不会消失.

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

int index = indexPath.row; id obj = [listOfItems objectAtIndex:index];

   UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

NSLog(@"%d",indexPath.row);
if (rowNO!=indexPath.row) {
    rowNO=indexPath.row;
    [self.tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;

    cell.accessoryView = [[ UIImageView alloc ]
                            initWithImage:[UIImage imageNamed:@"icon-tick.png" ]];

    [self.tableView cellForRowAtIndexPath:lastIndexPth].accessoryType=UITableViewCellAccessoryNone;
    lastIndexPth=indexPath;
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*sen 8

更清洁,更酷的方式是覆盖UITableViewCell,如下所示:

- (void)setAccessoryType:(UITableViewCellAccessoryType)accessoryType
{
    // Check for the checkmark
    if (accessoryType == UITableViewCellAccessoryCheckmark)
    {
        // Add the image
        self.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"YourImage.png"]] autorelease];
    }
    // We don't have to modify the accessory
    else
    {
        [super setAccessoryType:accessoryType];
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您已经这样做,则可以继续使用,UITableViewCellAccessoryCheckmark因为您的类会自动将其替换为图像.

您应该只在cellForRowAtIndexPath方法中设置样式.像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // [init subclassed cell here, dont forget to use the table view cache...]

    cell.accessoryType = (rowNO != indexPath.row ? nil : UITableViewCellAccessoryCheckmark);

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

然后,你只需要更新rowNOdidSelectRowAtIndexPath更新数据,并重绘细胞,就像这样:

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

    if (rowNO != indexPath.row)
    {
        rowNO = indexPath.row;
    }

    [self.tableView reloadData]; 

}
Run Code Online (Sandbox Code Playgroud)

此外,[self.tableView reloadData]您只能使用重新加载改变其样式(例如复选标记)的两个单元格,而不是重新加载整个表格reloadRowsAtIndexPaths.