UITableView常用属性

来源:互联网 发布:上海杏和软件实施 编辑:程序博客网 时间:2024/05/10 02:13

UITableView :Controller控制器 + ViewCell视图内容 + Model数据模型

UITableView代码创建ViewCell

[Toc]

1. 创建tableView

/** 表格视图 */@property (nonatomic, strong) UITableView *tableView; self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];//Plain悬停 Grouped不悬停

2. 设置数据源 和 数据数组(懒加载)

  • 设置数据源和代理,遵守协议 <UITableViewDataSource,UITableViewDelegate>
self.tableView.dataSource = self;// 数据源self.tableView.delegate = self;// 代理 
  • 懒加载:(字典数组转模型数组 或用 MJExtension 字典转模型框架)
    • 定义数据数组:
      /* 数据数组 */
      @property (nonatomic, strong) NSMutableArray *dataArray;
    • 加载Plist文件(解析)
#import "MJExtension.h"// 字典转模型框架// 懒加载- (NSMutableArray *)dataArray{     if (!_dataArray) {        // 方法一 :        // 1.加载字典数组(Plist文件解析)        NSArray *fileArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cars.plist" ofType:nil]];        // 2.创建临时数组        NSMutableArray *temp = [NSMutableArray array];        // 3.字典数组转模型数组        for (NSDictionary *dict in fileArr) {                LNCarGroup *carGroup = [LNCarGroup carGroupWithDict:dict];            [temp addObject:carGroup];        }         _dataArray = temp;        // 方法二 :        // MJExtension字典转模型框架        // [LNCarGroup mj_setupObjectClassInArray:^NSDictionary *{                // return @{@"cars" : [LNCar class]};        // }];        _dataArray = [LNCarGroup mj_objectArrayWithFilename:@"cars.plist"];        // 假设是从网络请求下来的        //_dataArray = [LNCarGroup mj_objectArrayWithKeyValuesArray:fileArr];     }     return _dataArray;}
  • 实现协议方法:section,row,cell
    • numberOfSectionsInTableView: 多少区
    • numberOfRowsInSection: 多少行
    • cellForRowAtIndexPath: 行内容

3. 创建ViewCell

  • 定义模型类对象
//  LNTgCell.h#import <UIKit/UIKit.h>@class LNTgModel;// 先声明@interface LNTgViewCell : UITableViewCell/* 模型类对象 */@property (nonatomic, strong) LNTgModel *tg;@end
  • ViewCell.m
    • 定义子控件属性
@interface LNTgViewCell ()/** 图片 */@property (nonatomic, weak) UIImageView *iconImageView;/** 标题 */@property (nonatomic, weak) UILabel *titleLabel;/** 价格 */@property (nonatomic, weak) UILabel *priceLabel;/** 购买数 */@property (nonatomic, weak) UILabel *buyCountLabel;/** 自定义分割线 */@property (nonatomic, strong) UILabel *lineLabel;@end
      1. 添加子控件 2. 设置子控件的frame 3. 设置子控件的数据(赋值)
/** *  1.添加子控件 (通过代码自定义cell要在这个方法中添加子控件) */- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {    }    return self;}// 2.设置子控件的frame- (void)layoutSubviews{    [super layoutSubviews];}/** *  3.设置子控件的数据(赋值) */- (void)setTg:(LNTgModel *)tg{    _tg = tg;}

4. 创建模型类

  • 定义模型属性
//  LNCarGroup.h#import <Foundation/Foundation.h>@interface LNCarGroup : NSObject// 1.定义模型属性/* 标题 */@property (nonatomic, copy) NSString *title;/* 车数组 */@property (nonatomic, strong) NSArray *cars;// *用MJExtension字典转模型框架,下面可以不写*// 2.提供构造方法+ (instancetype)carGroupWithDict:(NSDictionary *)dict;@end
//  LNCarGroup.m#import "LNCar.h"@implementation LNCarGroup// *用MJExtension字典转模型框架,下面可以不写*// 2.提供构造方法/*+ (instancetype)carGroupWithDict:(NSDictionary *)dict{    // 1.字典赋值模型属性    LNCarGroup *carGroup = [[LNCarGroup alloc] init];    carGroup.title = dict[@"title"];    //2.字典数组转模型数组    //(1.加载字典数组dict)    //(2.创建临时数组)    //(3.临时数组赋值模型数组)    NSMutableArray *temp = [NSMutableArray array];    for (NSDictionary *dic in dict[@"cars"]) {        LNCar *car = [LNCar carWithDic:dic];        [temp addObject:car];    }    carGroup.cars = temp;    return carGroup;}*/@end

tableView常用属性 + DataSource和Delegate

学写代码

1. UITableView表格视图

////  ViewController.m//  01-UITableView表格视图/* 1> plist解析:  以后遇到像这种复杂的plist,一层一层的往下解析.  最终的目的就是将所有的字典转成模型.  如果plist中字典在一个数组中,将来转出来的模型也放在一个数组中.  也就是将字典数组转成模型数组. 2> plist的好处:方便管理数据*//*UITableView1.创建tableView2.设置数据源DataSource:(1.遵守数据源协议:UITableViewDataSource)(2.实现协议方法:section,row,cell)*+3.创建模型类(1.定义模型属性)(2.提供构造方法(对象方法和类方法))(2.1字典赋值模型属性)(2.2字典数组转模型数组)4.懒加载*+(1.加载字典数组(Plist文件解析))(2.创建模型数组(临时数组))(3.字典数组转模型数组)5.DataSource协议方法section row cell1.区(数据数组dataArray.count)2.行(模型数组.count)3.行内容(取出对应模型属性赋值indexPath.section/indexPath.row)6.MJExtension字典转模型框架*+附:+7.ViewCell   (1.定义模型类对象)   (2.定义子控件属性)   (3.在initWithStyle:style reuseIdentifier:reuseIdentifier,添加子控件(设置约束Masonry))   (4.模型类对象set方法setTg:设置子控件的数据(赋值))8.MJExtension字典转模型框架9.自定义分割线*+10.优化点:所有的创建,都像懒加载一样写*+*/#import "ViewController.h"#import "LNCarGroup.h"#import "LNCar.h"#import "MJExtension.h"// 字典转模型框架@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>/* 表格视图 */@property (nonatomic, strong) UITableView *tableView;/* 数据数组 */@property (nonatomic, strong) NSMutableArray *dataArray;@end@implementation ViewController// 懒加载- (NSMutableArray *)dataArray{    if (!_dataArray) {        /*        // 1.加载字典数组(Plist文件解析)        NSArray *fileArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cars.plist" ofType:nil]];        // 2.创建临时数组        NSMutableArray *temp = [NSMutableArray array];        // 3.字典数组转模型数组        for (NSDictionary *dict in fileArr) {            LNCarGroup *carGroup = [LNCarGroup carGroupWithDict:dict];            [temp addObject:carGroup];        }        _dataArray = temp;        */        // MJExtension字典转模型框架//        [LNCarGroup mj_setupObjectClassInArray:^NSDictionary *{//            return @{@"cars" : [LNCar class]};//        }];        _dataArray = [LNCarGroup mj_objectArrayWithFilename:@"cars.plist"];        // 假设是从网络请求下来的        //_dataArray = [LNCarGroup mj_objectArrayWithKeyValuesArray:fileArr];    }    return _dataArray;}- (void)viewDidLoad {    [super viewDidLoad];    [self createTableView];}// 隐藏状态栏- (BOOL)prefersStatusBarHidden{    return YES;}- (void)createTableView{    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];//Plain悬停 Grouped不悬停    self.tableView.dataSource = self;// 数据源    self.tableView.delegate = self;// 代理    [self.view addSubview:self.tableView];    // 方法二:    // 1.tableView注册    [self.tableView registerClass:[LNTgViewCell class] forCellReuseIdentifier:tgID];/**---------- 常见属性 --------------**/    // 全局设置行row高    _tableView.rowHeight = 100;    // 全局设置区头(区尾)高    _tableView.sectionHeaderHeight = 50;    _tableView.sectionFooterHeight = 50;    // 设置分割线的样式和颜色    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;    _tableView.separatorColor = [UIColor redColor];    // 设置tableView表格头(尾)视图    _tableView.tableHeaderView = [[UISwitch alloc] init];    _tableView.tableFooterView = [[UISwitch alloc] init];    // 隐藏系统分割线,自定义分割线    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    // 隐藏多余分割线*+    self.tableView.tableFooterView = [[UIView alloc] init];    // 背景视图和颜色    _tableView.backgroundView = [[UIView alloc] init];    _tableView.backgroundColor = [UIColor grayColor];    // 设置TableView的cell的预设高度*+ (性能优化)    self.tableView.estimatedRowHeight = 20;    // 索引文字和背景颜色*+    _tableView.sectionIndexColor = [UIColor grayColor];    _tableView.sectionIndexBackgroundColor = [UIColor yellowColor];    // 自定义cell线    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectZero];    lineLabel.textColor = [UIColor clearColor];    lineLabel.backgroundColor = [UIColor colorWithRed:29 green:29 blue:38 alpha:0.05];    [self.contentView addSubview:lineLabel];    [lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {        make.bottom.equalTo(self.contentView.mas_bottom).with.offset(0);        make.left.equalTo(self.contentView.mas_left).with.offset(0);        make.right.equalTo(self.contentView.mas_right).with.offset(0);        make.height.mas_equalTo(1.0f);    }];}#pragma mark - UITableViewDataSource// 多少区section- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return self.dataArray.count;}// 多少行row(section对应模型属性)- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    LNCarGroup *carGroup = self.dataArray[section];    return carGroup.cars.count;}// 行内容cell- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    /*    // 方法一:    // 1.设置cellID标识    static NSString *cellID = @"cellID";    // 2.cell复用队列    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];    }    // 3.设置数据(取出对应模型属性赋值)    LNCarGroup *carGroup = self.dataArray[indexPath.section];    LNCar *car = carGroup.cars[indexPath.row];    cell.textLabel.text = car.name;    cell.imageView.image = [UIImage imageNamed:car.icon];*/    // 方法二:(需要先注册)    // 2.cell复用队列(访问缓存池)    LNTgViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tgID];    // 3.设置数据(数据数组赋值给模型类)    cell.tg = self.dataArray[indexPath.row];    // 附加样式(比如右侧的箭头)    cell.accessoryType = UITableViewCellAccessoryCheckmark;    // 设置右侧显示的控件    cell.accessoryView = [[UISwitch alloc] init];    cell.selectionStyle = UITableViewCellSelectionStyleGray;    // 设置cell的背景颜色    cell.backgroundColor = [UIColor clearColor];// 透明    // 选中时背景视图    UIView *view = [[UIView alloc] init];    view.backgroundColor = [UIColor grayColor];    cell.selectedBackgroundView = view;    NSLog(@"-----%p %ld",cell,indexPath.row);    return cell;}#pragma mark - UITabelViewDelegate// 行高- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    // 获取indexPath    //    if (indexPath.row%2) {    //        return 100;    //    }else    NSLog(@"heightForRowAtIndexPath");    return 100;    }// 选中- (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);    //}// 设置不同区section的头部高度*+- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{     switch (section) {        case 0:            return 100;            break;        case 3:            return 80;            break;        default:            return 44;            break;    }}// 区头(区尾)标题- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{    LNCarGroup *carGroup = self.dataArray[section];    return carGroup.title;}// 区头(区尾)View(会覆盖sectionTitle)//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{//    UIView *View = [[UIView alloc] init];//    View.backgroundColor = [UIColor grayColor];//    return View;//}// 索引*+-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{     // 遍历数据数组取模型属性//    NSMutableArray *titlesArr = [NSMutableArray array];//    for (LNCarGroup *group in self.dataArray) {//        [titlesArr addObject:group.title];//    }//    return titlesArr;     return [self.dataArray valueForKeyPath:@"title"];}// cell的预设高度//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 20;}@end

2. tableView修改数据(模型)显示

/*////  ViewController.m//  01-tableView学习点10.16/* 1.tableView修改数据  1.修改模型数组  2.刷新表格  (1.全局刷新:[self.tableView reloadData])  (2.局部刷新:更新reloadRowsAtIndexPaths, 添加insertRowsAtIndexPaths , 删除deleteRowsAtIndexPaths) 2.左滑删除(默认Delete):commitEditingStyle 3.自定义左滑显示按钮:editActionsForRowAtIndexPath*+ 4.进入编辑模式(取反,左侧出现减号按钮)*+ 5.tableView在编辑模式下可以多选(多行删除)*+   self.tableView.allowsMultipleSelectionDuringEditing = YES; 6.自定义批量删除*+ 总结点:通过模型来修改cell的显示内容*+ */#import "ViewController.h"#import "LNWineCell.h"#import "MJExtension.h"#import "LNWine.h"@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>@property (weak, nonatomic) IBOutlet UITableView *tableView;@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;// 批量删除@property (weak, nonatomic) IBOutlet UIButton *batchDeleteBtn;// 删除@property (weak, nonatomic) IBOutlet UIButton *customDeleteBtn;// 自批量删除/* 数据数组 */@property (nonatomic, strong) NSMutableArray *dataArray/** 记录用户选中行的索引 */@property (nonatomic, strong) NSMutableArray *seletedIndexPathArr;@end@implementation ViewController- (NSMutableArray *)dataArray{    if (!_dataArray) {        _dataArray = [LNWine mj_objectArrayWithFilename:@"wine.plist"];    }    return _dataArray;}- (NSMutableArray *)seletedIndexPathArr{    if (!_seletedIndexPathArr) {        _seletedIndexPathArr = [NSMutableArray array];    }    return _seletedIndexPathArr;}NSString *cellID = @"cellID";- (void)viewDidLoad {    [super viewDidLoad];    self.batchDeleteBtn.hidden = YES;    //self.tableView.rowHeight = 60;    self.tableView.estimatedRowHeight = 100;    self.tableView.dataSource = self;    self.tableView.delegate = self;    // 分割线    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    // tableView在编辑模式下可以多选*+(想要多行删除,要设置这点属性)    self.tableView.allowsMultipleSelectionDuringEditing = YES;    // 1.注册    [self.tableView registerClass:[LNWineCell class] forCellReuseIdentifier:cellID];}// 添加- (IBAction)add:(UIButton *)button {    // 1.修改模型数组    LNWine *wine = [[LNWine alloc] init];    wine.image = @"newWine";    wine.money = @"6.15";    wine.name = @"女二红";    [self.dataArray insertObject:wine atIndex:0];    // 2.刷新表格    //[self.tableView reloadData];    // 添加局部刷新*+    NSArray *indexPaths = @[                            [NSIndexPath indexPathForRow:0 inSection:0],                            ];    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];}// 删除- (IBAction)remove:(UIButton *)button {    /*    // 1.修改模型数组    [self.dataArray removeObjectAtIndex:0];    // 2.刷新表格    //[self.tableView reloadData];    // 添加局部刷新*+    NSArray *indexPaths = @[                            [NSIndexPath indexPathForRow:0 inSection:0],                            ];    [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];    */    // 进入编辑模式(取反,左侧出现减号按钮)*+    [self.tableView setEditing:!self.tableView.editing animated:YES];    self.batchDeleteBtn.hidden = !self.tableView.editing;}// 批量删除- (IBAction)batchDelete:(UIButton *)sender {    NSMutableArray *tempArray = [NSMutableArray array];    for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {        [tempArray addObject:self.dataArray[indexPath.row]];    }    // 1.    [self.dataArray removeObjectsInArray:tempArray];    // 2.    [self.tableView deleteRowsAtIndexPaths:self.tableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationAutomatic];}// 自定义批量删除- (IBAction)customDelete:(UIButton *)sender {    // 仿系统写法    // 获取要删除的酒模型    NSMutableArray *tempArray = [NSMutableArray array];    for (NSIndexPath *indexPath in self.seletedIndexPathArr) {        [tempArray addObject:self.dataArray[indexPath.row]];    }    // 1.删除模型    [self.dataArray removeObjectsInArray:tempArray];    // 2.刷新表格    [self.tableView deleteRowsAtIndexPaths:self.seletedIndexPathArr withRowAnimation:UITableViewRowAnimationAutomatic];    // 清空数组*+    [self.seletedIndexPathArr removeAllObjects];}// 更新- (IBAction)update:(UIButton *)button {    // 1.修改模型数组    LNWine *wine = self.dataArray[0];    wine.money = @"6.15-8.17";    LNWine *wine1 = self.dataArray[1];    wine1.name = @"刘楠";    // 2.刷新表格    //[self.tableView reloadData];    // 局部更新*+    NSArray *indexPaths = @[                            [NSIndexPath indexPathForRow:0 inSection:0],                            [NSIndexPath indexPathForRow:1 inSection:0],                            ];    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];}#pragma mark - UITableViewDataSource- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return self.dataArray.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    // 2.cell复用队列    LNWineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];    // 3.设置数据(对应数据数组赋值模型类)    cell.wine = self.dataArray[indexPath.row];    NSLog(@"cellForRowAtIndexPath--%zd",indexPath.row);    return cell;}#pragma mark - 代理方法// 解决方案:在这个方法返回之前就要计算cell的高度*+- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    LNWine *wine = self.dataArray[indexPath.row];    return wine.cellHeight;}/*// 只要实现这个方法,就拥有左滑删除功能*+// 点击左滑出删除按钮,会调用这个方法// 下两个方法只是作用默认的左滑出删除按钮- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    NSLog(@"commitEditingStyle---");    // 1.    [self.dataArray removeObjectAtIndex:indexPath.row];    // 2.    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];}// 修改默认Delete按钮的文字- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{    return @"删除";}*/#pragma mark - 自定义左滑显示按钮*+- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"关注" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {        // 退出编辑模式*+        self.tableView.editing = NO;    }];    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {        // 1.修改模型数组        [self.dataArray removeObjectAtIndex:indexPath.row];        // 2.刷新表格        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];    }];    return @[action1,action];}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    // 1.修改模型(创建一个数组存放选中的row)    LNWine *wine = self.dataArray[indexPath.row];    if (wine.checked) {// 之前是打钩的,取消打钩        wine.checked = NO;        [self.seletedIndexPathArr removeObject:indexPath];    } else {// 之前不是打钩的,现在打钩        wine.checked = YES;        [self.seletedIndexPathArr addObject:indexPath];    }    // 2.刷新表格    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];}@end
  • 字符串自适应宽高
// 价格// 字符串自适应宽高(文字有换行)*+CGFloat moneyX = nameX;CGFloat moneyY = CGRectGetMaxY(self.nameFrame) + space;CGFloat textW = [UIScreen mainScreen].bounds.size.width - 6 * space -24;NSDictionary *textAtt = @{NSFontAttributeName : [UIFont systemFontOfSize:14]};// 最大宽度是textW,高度不限制CGSize textSize = CGSizeMake(textW, MAXFLOAT);CGFloat textH = [self.money boundingRectWithSize:textSize options:NSStringDrawingUsesLineFragmentOrigin attributes:textAtt context:nil].size.height;self.moneyFrame = CGRectMake(moneyX, moneyY, textW, textH);

效果图

  • tableView常用属性效果图

这里写图片描述

  • tableView修改数据(模型)显示

这里写图片描述

0 0
原创粉丝点击