ios - 选定行的自定义复选标记

标签 ios objective-c uitableview

我在“UITableViewCell”中使用自定义图像作为复选标记 -“iphone-checkMark@2x.png”,但它显示在单元格中的任何位置。谁能建议如何使其仅针对单个选定的单元格显示?

这是我的代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                         reuseIdentifier:CellIdentifier];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
    [cell.contentView addSubview:label];
    label.text = [tableArr objectAtIndex:indexPath.row];
    label.font = [UIFont fontWithName:@"Whitney-Light" size:20.0];
    label.tag = 1;
    UIImageView *checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iphone-checkMark@2x.png"]];
    cell.accessoryView = checkmark;
    return cell;
}

最佳答案

代码越少越好:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                         reuseIdentifier:CellIdentifier];
 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}


cell.textLabel.text = [tableArr objectAtIndex:indexPath.row];
cell.textLabel = [UIFont fontWithName:@"Whitney-Light" size:20.0];
return cell;

更新:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  lastIndexPath = indexPath;
  [tableView reloadData];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
            if ([lastIndexPath isEqual:indexPath]) {
                cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iphone-checkMark.png"]];
            } else {
                cell.accessoryView = nil;
            }    
}

更新 2:

//dont forget check for nil
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:lastIndexPath forKey:@"lastIndexPath"]; 
[defaults synchronize];

阅读

NSIndexPath *lastPath = [defaults valueForKey:@"lastIndexPath"];

关于ios - 选定行的自定义复选标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16904666/

相关文章:

iOS 8 UITableViewRowAction : Swipe Left, 图片?

ios - 在容器 View 上添加 ViewController 时, TableView 动画无法正常工作?

ios - 如何阻止在 iMessage 中选择贴纸

iOS Storyboard : Not able to instantiate view controller properly

objective-c - ARC 是否支持调度队列?

Java 与 Objective-c UTF-8 编码

ios - 一旦录音机使用 AudioKit 在 Swift 中完成录音,如何实现监听器或 while(true) 以停止滚动波形图

ios - Coreplot折线图线不可见

iphone - 如何连接 iPhone 和网络服务并获取 XML 数据?

ios - 向 tableView 添加行不起作用