iOS开发笔记-UITableView的单选

来源:互联网 发布:php和java哪个好找工作 编辑:程序博客网 时间:2024/05/01 01:55

好吧,很久以前写的,现在把它整理出来给那些需要的人


//

//  JPViewController.m

//  SingleSelectedDemo

//

//  Created by kuaitu on 15/1/9.

//  Copyright (c) 2015 JP. All rights reserved.

//


#import "JPViewController.h"


@interfaceJPViewController ()


@end


@implementation JPViewController

{

    int _row;

    int _rowNum;

}

- (void)viewDidLoad

{

    [super viewDidLoad];


    //记录上次选择的结果

    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"select"];

    

    _row = [str intValue];


    UITableView *tableView = [[UITableViewalloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)style:UITableViewStyleGrouped];


    tableView.delegate =self;

    tableView.dataSource = self;


    [self.viewaddSubview:tableView];

}

#pragma mark - UITableViewDatasource


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

{

    return 20;

}

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

{

    static NSString *cellIdentifier = @"cell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    

    if (cell == nil)

    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    

    cell.tintColor = [UIColor redColor];

    if ( _rowNum == indexPath.row)

    {

        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    }

    else

    {

        cell.accessoryType = UITableViewCellAccessoryNone;

    }

    

    cell.textLabel.text = @"111";

    return cell;

}



#pragma mark - UITableViewDelegate


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 50;

}

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

{

    NSLog(@"111111");

 

    _rowNum = indexPath.row;

    

    [tableView reloadData];


    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"select"];

    [[NSUserDefaults standardUserDefaults] synchronize];

    

    

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


0 0
原创粉丝点击