D13:自定义UITableViewCell

自定义Cell时Cell的控件都是添加到Cell的contentView上
KVC方法设置属性值, 快速创建数据源

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues
[model setValuesForKeysWithDictionary:dict];

使用XIB方式时新建Cell对象时使用

- (NSArray *)loadNibNamed:(NSString *)name owner:(id)owner options:(NSDictionary *)options
cell = [[[NSBundle mainBundle] loadNibNamed:@"BookCell" owner:self options:nil] lastObject];


一.代码自定义 "UITableViewCell"

题目要求:根据plist文件准备数据源, 并创建模型
  1. 根据需求和plist文件创建模型类

  • 创建数据源(数据源数组中的数据是模型对象): 从plist文件中获取数据

  • 新建tableView

  • 核心:自定义Cell

    // 自定义cell
    // 继承于UITableViewCell创建一个类型
    // 然后添加需要的视图, 用来显示数据
    @interface BookCell : UITableViewCell
    
    // 左边的图片, 需要注意: 不要和父类的imageView属性冲突
    @property (nonatomic, strong) UIImageView *bookImageView;
    // 书名,      需要注意: 不要和父类的textLabel和DetailTextLable属性冲突
    @property (nonatomic, strong) UILabel *nameLabel;
    // 价格
    @property (nonatomic, strong) UILabel *prcieLabel;
    // 描述
    @property (nonatomic, strong) UILabel *descLabel;
    
    // 显示数据
    - (void)config:(BookModel *)model;
    
    @end
    
    
    • 重写- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
      - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            // 初始化视图对象
            // 图片
            _bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 60, 60)];
            // 添加到父视图
            // 自定义cell的时候, 所有视图都添加到cell的contentView中
            [self.contentView addSubview:_bookImageView];
            
            // 书名
            _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 5, 200, 20)];
            [self.contentView addSubview:_nameLabel];
            
            // 价格
            _prcieLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 30, 200, 20)];
            [self.contentView addSubview:_prcieLabel];
            
            // 描述
            _descLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 55, 200, 20)];
            [self.contentView addSubview:_descLabel];
        }
        return self;
    }
    
    
    • 自定义Cell中显示数据的方法
      - (void)config:(BookModel *)model
      {
          self.bookImageView.image = [UIImage imageNamed:model.icon];
          self.nameLabel.text = model.name;
          self.prcieLabel.text = model.price;
          self.descLabel.text = model.detail;
      }
    
  • DataSource方法

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellID = @"cellID";
        BookCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (nil == cell) {
            cell = [[BookCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        }
        [cell config:self.dataArray[indexPath.row]];
        
        return cell;
    }
    

二. 代码自定义Cell为一个ScrollView加上其他控件的效果

  1. 初步创建广告数据的模型类
    #import <Foundation/Foundation.h>
    
    @interface AdModel : NSObject
    
    // 图片
    @property (nonatomic, strong) NSString *imageName;
    // 标题文字
    @property (nonatomic, strong) NSString *title;
    
    @end  
    
  2. 准备广告cell的数据源

    @property (nonatomic, strong) NSMutableArray *adArray;

    // 创建广告cell对应的数据
    - (void)createAdvertisementData
    {
        // 数据源数组
        _adArray = [NSMutableArray array];
        
        for (int i = 0; i < 4; i++) {
            AdModel *model = [[AdModel alloc] init];
            model.imageName = [NSString stringWithFormat:@"image%d", i];
            model.title = [NSString stringWithFormat:@"第%d个标题", i+1];
            [_adArray addObject:model];
        }
    
    }
      
    
  3. 核心: 自定义Cell

    • AdCell.h
    @interface AdCell : UITableViewCell
        
    // 滚动视图, 用来显示图片
    @property (nonatomic, strong) UIScrollView *scrollView;
    // 底部的背景视图(只需显示颜色)
    @property (nonatomic, strong) UIView *bgView;
    // 标题文字
    @property (nonatomic, strong) UILabel *titleLabel;  
    // UIPageControl
    @property (nonatomic, strong) UIPageControl *pageCtrl;
    
    // 显示数据(如果是之前的config: 方法, 相当于只是setter方法)
    @property (nonatomic, strong) NSArray *adArray;
        
    @end
        
    
    • AdCell.m
   #import "AdCell.h"
   #import "AdModel.h"
   #define kHeightOfStatusBar 20
   #define kHeightOfAssemble 44
   #define kHeightOfNavigationAndStatusBar 64
   #define kBoundsOfScreen [[UIScreen mainScreen] bounds]
   #define kWidthOfScreen [[UIScreen mainScreen] bounds].size.width
   #define kHeightOfScreen [[UIScreen mainScreen] bounds].size.height
   
   @implementation AdCell
   
   // 重写父类的方法
   - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
   {
       self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
       if (self) {
           // 初始化视图
           // 1. 滚动视图
           _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidthOfScreen, 160)];
           [self.contentView addSubview:_scrollView];
           
           // 2. 背景视图
           _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 130, kWidthOfScreen, 30)];
           _bgView.backgroundColor = [UIColor grayColor];
           // 设置透明度
           _bgView.alpha = 0.5;
           [self.contentView addSubview:_bgView];
           
           // 3. 标题文字
           _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 130, 120, 30)];
           _titleLabel.textColor = [UIColor whiteColor];
           [self.contentView addSubview:_titleLabel];
           
           // 4. pageCtrl
           _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(160, 130, kWidthOfScreen - 180, 30)];
           [self.contentView addSubview:_pageCtrl];
       }
       return self;
   }
   
   // 重新实现setter方法
   - (void)setAdArray:(NSArray *)adArray
   {
       _adArray = adArray;
       
       // 添加额外的功能
       // 1.滚动视图: 显示4张图片
       for (int i = 0; i < adArray.count; i++) {
           // 创建图片视图对象
           AdModel *model = adArray[i];
           UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*kWidthOfScreen, 0, kWidthOfScreen, CGRectGetHeight(self.scrollView.frame))];
           imageView.image = [UIImage imageNamed:model.imageName];
           //UIViewContentModeScaleToFill:图片被拉伸(比例可能不变)以充满整个imageView
           //UIViewContentModeScaleAspectFit:图片被拉伸,比例不变,图片的长边刚好与imageview一样
           //UIViewContentModeScaleAspectFill:图片被拉伸,比例不变,图片的短边与imageview一致,图片有可能超出imageview
           imageView.contentMode = UIViewContentModeScaleAspectFit;
           [self.scrollView addSubview:imageView];
       }
       self.scrollView.contentSize = CGSizeMake(kWidthOfScreen*adArray.count, 160);
       
       // 2. 背景视图无需改动
       
       // 3. 标题文字
       if (adArray.count > 0) {
           AdModel *model = adArray[0];
           // 显示标题
           self.textLabel.text = model.title;
       }
   
       // 4. pageCtrl
       _pageCtrl.numberOfPages = adArray.count;
       _pageCtrl.currentPage = 0;
   }
  • 修改tableView相关协议方法的实现, 使其能够显示
    #pragma mark - DataSource
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
    //    return self.dataArray.count;
        // 广告的显示占一个Cell
        return self.dataArray.count + 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.row == 0) {
            // 广告cell
            static NSString *adCellID = @"adCell";
            AdCell *cell = [tableView dequeueReusableCellWithIdentifier:adCellID];
            if (nil == cell) {
                cell = [[AdCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:adCellID];
            }
            
            cell.adArray = self.adArray;
            
            return cell;
        }
        // 书籍cell
        static NSString *cellID = @"cellID";
        BookCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (nil == cell) {
            cell = [[BookCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        }
        [cell config:self.dataArray[indexPath.row - 1]];
        
        return cell;
    }
    
    #pragma mark - Delegate
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.row == 0) {
            // 广告cell
            return 160;
        }
        return 80;
    }
    

三. xib方式自定义Cell

  1. 创建模型, 创建导航栏, 普通方法创建数据源

  • kvc方法设置属性值

    • 普通方法创建数据源

model.title = dict[@"title"];
model.icon = dict[@"icon"];
model.price = dict[@"price"];
model.detail = dict[@"detail"];
```

  • 用KVC方法设置属性值, 快速创建数据源

// 用字点数据转成对象时, 如果字典的key值和对象的属性名称一一对应, 可以用kvc来设置属性值
[model setValuesForKeysWithDictionary:dict];
```

  • 创建tabview对象,遵守协议实现协议方法

  • 完成自定义cell前工作

  • 创建BookCell(切记设置Cell的重用标记)

XIB连线图
  • 创建滚动视图的模型和广告cell的数据源

 /*
         第一个参数: xib文件的名字
         第二个参数: 对象的所有者(可以传self, 也可以传nil)
         第三个参数: 选项参数(传nil)
         */
        cell = [[[NSBundle mainBundle] loadNibNamed:@"BookCell" owner:self options:nil] lastObject];
  • 创建并书写完成AdCell(切记设置AdCell的重用标记)

XIB连线图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容