所选行的自定义复选标记

时间:2013-06-03 19:46:54

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

更少的代码更好:

- (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"];

答案 1 :(得分:0)

实现您要做的事情的一种方法是使用按钮并将背景图像设置为您的复选框。这个按钮将是你的accessoryView。监视按钮上的触摸事件并相应地显示布尔值。以下链接中的示例项目将提供实现此目的所需的所有代码。 https://developer.apple.com/library/ios/#samplecode/Accessory/Introduction/Intro.html

相关问题