IOS-UITableView入门(二)

IOS-UITableView入门(2)

1.对于TableView ,每个item的视图基本都是一样的。不同的只有数据。

IOS提供了一种缓存视图跟数据的方法。在 -UITableViewCell *) tableView:cellForRowAtIndexPath:

//创建一个用于缓存的标示
    static NSString *ID=@"CellTable";
    //先从缓存中取得UITableViewCell
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //如果取不到,则代码创建。
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }

2

//创建系统提供的每个item右边的图标
        cell.accessoryType=UITableViewCellAccessoryCheckmark;

3.通过动画修改某个item的显示

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

4.通过动画删除某个item

[self.tableView deleteRowsAtIndexPaths:self.indexPaths withRowAnimation:UITableViewRowAnimationLeft];

CSZViewController.h 整体代码如下:声明TableView的协议和数据源

#import <UIKit/UIKit.h>

@interface CSZViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

- (IBAction)trashClick:(id)sender;

@end

CSZViewController.m 有关TableView代码如下:

#pragma mark - dataSource
#pragma mark 每列行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

#pragma mark 创建每行的View
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //创建一个用于缓存的标示
    static NSString *ID=@"CellTable";
    //先从缓存中取得UITableViewCell
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //如果取不到,则代码创建。
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.textLabel.text=self.array[indexPath.row];
    cell.detailTextLabel.text=@"description....";
    
    if ([self.deleteArr containsObject:cell.textLabel.text]) {
        //创建系统提供的每个item右边的图标
        cell.accessoryType=UITableViewCellAccessoryCheckmark;
    }else
    {
        cell.accessoryType=UITableViewCellAccessoryNone;
    }
    
    return  cell;
    
}

#pragma mark - UITableViewDelegate
#pragma mark 点击每个item调用
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([self.deleteArr containsObject:self.array[indexPath.row]]) {
        [self.deleteArr removeObject:self.array[indexPath.row]];
        [self.indexPaths removeObject:indexPath];
    }else
    {
        [self.deleteArr addObject:self.array[indexPath.row]];
        [self.indexPaths addObject:indexPath];
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

#pragma mark 返回每行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}