UITableView accessoryType single check

 做了一个单选勾选的表之前有些问题,修改了一下

.h文件
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{

    NSArray *arrry;
    NSInteger checkedIndexPath;  

}
@end
- (void)viewDidLoad
{
    [super viewDidLoad];
    UITableView *atable=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 350)];
    atable.delegate=self;
    atable.dataSource=self;
    checkedIndexPath=-1;
    [self.view addSubview:atable];
    arrry=[[NSArray alloc] initWithObjects:@"1",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2",@"2", nil];
    
}

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

    static NSString *cellinde=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellinde];
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellinde];
    }


    cell.accessoryType=UITableViewCellAccessoryNone;

    
    cell.textLabel.text=[arrry objectAtIndex:indexPath.row];
    if (checkedIndexPath==indexPath.row) {
        cell.accessoryType=UITableViewCellAccessoryCheckmark;
    }

return cell;


}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{


    return [arrry count];
}

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

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (checkedIndexPath)
    {
        if (indexPath.row==checkedIndexPath) return;
        UITableViewCell *uncheckCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:checkedIndexPath inSection:0]];
        [uncheckCell setAccessoryType:UITableViewCellAccessoryNone];
    }
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    checkedIndexPath = indexPath.row;

    
    
}
原文地址:https://www.cnblogs.com/leeAsia/p/3342153.html