用自定义图像替换UITableView的默认复选标记

far*_*t99 6 objective-c uitableview ios

我想替换UITableViewCell附件设置为时显示的默认复选标记图像:UITableViewCellAccessoryCheckmark.

所以我还是想写:

[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
Run Code Online (Sandbox Code Playgroud)

但是我想要显示自己的图像而不是默认图像.

任何帮助深表感谢.

Par*_*att 4

方法一:

我想你可以使用

假设您有一个带有复选标记图像的 UIButton。

cellForRowAtIndexPath:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];

[button addTarget:self action:@selector(checkButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
Run Code Online (Sandbox Code Playgroud)

checkButtonTapped:事件:方法:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
}
Run Code Online (Sandbox Code Playgroud)

accessoryButtonTappedForRowWithIndexPath:方法

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];

    BOOL checked = [[item objectForKey:@"checked"] boolValue];

    [item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];

    UITableViewCell *cell = [item objectForKey:@"cell"];
    UIButton *button = (UIButton *)cell.accessoryView;

    UIImage *newImage = (checked) ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];
}
Run Code Online (Sandbox Code Playgroud)

我从这个链接中获取了上面的代码:

在 iPhone 中为 UITableView 实现自定义配件视图

方法2:

还有一种方法可以使用自定义 tableView 单元格。

我认为你必须创建一个自定义单元格并在单元格的右侧添加一个 imageView 。

然后这个 imageView 将保存你想要的图像。

在 didSelectRowAtRowAtIndexPath: 上,您可以添加图像并根据点击次数删除图像。

如果您需要更多帮助,请告诉我。

希望这可以帮助。