UI控件 18 UITableView单元格

1.UITableViewCell:数据视图单元格类型
2.dequeueReusableCellWithIdentifier:获取可以复用的单元格对象
3.initWithStyle:根据风格创建单元格对象
4.reuseIdentifier:设置可以复用单元格的ID
AppDelegate.m文件实现:

#import "AppDelegate.h"
#import "ViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //先创建一个窗口 UIScreen mainScreen:获取屏幕的宽和高
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    //特别注意这里 [] 的设置
    //创建一个导航控制器
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:[[ViewController alloc]init]];
    
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end

ViewController.h文件声明:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
<
UITableViewDelegate,
UITableViewDataSource
>
{
    //数据视图
    UITableView * _tableView;
    
    //数据源 将来也可从网络服务器下载
    NSMutableArray * _arrayData;
    
    //添加导航按钮
    UIBarButtonItem * _btnEdit;
    UIBarButtonItem * _btnFinish;
    UIBarButtonItem * _btnDelete;
    //设置编辑状态 需要自己做一个导航控制器 去掉main那一项
    BOOL _isEdit;
}

@end

ViewController.m文件的实现:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //创造一个UITableView bounds:原型,界限
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    //自动调整子视图的大小
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    //设置代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    //数据视图的头部视图的设定
    _tableView.tableHeaderView = nil;
    
    //数据视图的尾部视图的设定
    _tableView.tableFooterView = nil;
    
    [self.view addSubview:_tableView];
    
    //初始化数据源数组
    _arrayData = [[NSMutableArray alloc]init];
    
    for (int i = 1; i < 20; i++) {
        NSString * str = [NSString stringWithFormat:@"A %d",i];
        
        //把这些产生的数据依次放在数组中
        [_arrayData addObject:str];
    }
    
    //当数据视图的数据源发生变化时,用来更新数据视图 reload:重写加载
    [_tableView reloadData];
    
    //在viewDidLoad函数中调用下面这些函数
    [self createBtn];
    
}

- (void)createBtn
{
    _isEdit = NO;
    
    //创建功能按钮
    _btnEdit = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(pressEdit)];
    _btnFinish = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(pressFinish)];
    _btnDelete = [[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(pressDelete)];
    
    self.navigationItem.rightBarButtonItem = _btnEdit;
}

//这个函数你什么都不干,只是写出来,就可以不按编辑键也可以出状态,当手指在单元格上移动时
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当然也可以在按下按钮时 进行事件的操作:
    //删除存在索引的数据源对应的数据 这样删除后界面并不会发生变化
    [_arrayData removeObjectAtIndex:indexPath.row];
    
    //如果想要界面发生变化: 则需要重新加载更新数据源
    [_tableView reloadData];
    
    NSLog(@"delete!");
}

//当选中单元格时 调用此协议函数 用户可自定义会发生的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选中单元格!%ld,%ld",indexPath.section,indexPath.row);
}

//当取消选中时,调用的协议函数 用户可自定义会发生的事件
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"取消选中单元格! %ld,%ld",indexPath.section,indexPath.row);
}


//单元格显示效果协议
//默认 文字为删除 Delete
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //删除状态:UITableViewCellEditingStyleDelete
    //插入状态:UITableViewCellEditingStyleInsert
    //虚空状态:UITableViewCellEditingStyleNone
    //组合多选状态:UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert
    return UITableViewCellEditingStyleDelete;
}


//功能1:当摁下Edit时 删除按钮出现在左上角 完成按钮出现在右上角 同时开启编辑状态
- (void)pressEdit
{
    _isEdit = YES;
    self.navigationItem.rightBarButtonItem = _btnFinish;
    //setEditing : 开启编辑状态
    [_tableView setEditing:YES];
    self.navigationItem.leftBarButtonItem = _btnDelete;
}

- (void)pressFinish
{
    //当按下完成按钮 左上角删除按钮和右上角完成按钮就会消失
    //右上角的编辑按钮又会重新出现 同时编辑状态会取消
    _isEdit = NO;
    self.navigationItem.rightBarButtonItem = _btnEdit;
    //setEditing : 取消编辑状态
    [_tableView setEditing:NO];
    self.navigationItem.leftBarButtonItem = nil;
}

//返回一共多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrayData.count;
}

//默认组数返回1
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 1;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * strID = @"ID";
    
    //dequeueReusableCellWithIdentifier: 尝试获取可复用的单元格
    //可复用:当一个单元格消失 会出现新的单元格代替消失的单元格
    //使用条件: 单元格足够多
    //如果得不到 返回为空
    UITableViewCell * cell = [_tableView dequeueReusableCellWithIdentifier:strID];
    
    if ( cell == nil ){
        //创建一个
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strID];
        //想要显示子标题只能通过SubtitlereuseIdentifier 状态
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:strID];
    }
    
    //单元格文字赋值  row 行数
    cell.textLabel.text = [_arrayData objectAtIndex:indexPath.row];
    //设置子文字标题
   // cell.detailTextLabel.text = @"子标题";
    
    //在单元格中显示图片
    NSString * str = [NSString stringWithFormat:@"%d.JPG",indexPath.row % 7+1];
    
    UIImage * image = [UIImage imageNamed:str];
    
   // UIImageView * iView = [[UIImageView alloc]initWithImage:image];
    //下面这个等价于上面注释的这个
    //设置默认的图标信息
    cell.imageView.image = image;
    
    return cell;
}

//修改单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

猜你喜欢

转载自blog.csdn.net/teropk/article/details/81393515