广

IOS开发

  • IOS开发
  • android开发
  • PHP编程
  • JavaScript
  • ASP.NET
  • ASP编程
  • JSP编程
  • Java编程
  • 易语言
  • Ruby编程
  • Perl编程
  • AJAX
  • 正则表达式
  • C语言
  • 编程开发

    iOS中使用UItableviewcell实现团购和微博界面的示例

    2018-04-05 08:32:55 次阅读 稿源:互联网
    广告

    使用xib自定义UItableviewcell实现一个简单的团购应用界面布局

    一、项目文件结构和plist文件

    二、实现效果

    三、代码示例

    1.没有使用配套的类,而是直接使用xib文件控件tag值操作

    数据模型部分:

    YYtg.h文件
    代码如下:

    //
    //  YYtg.h
    //  01-团购数据显示(没有配套的类)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import <Foundation/Foundation.h>
    #import "Global.h"

    @interface YYtg : NSObject
    @property(nonatomic,copy)NSString *buyCount;
    @property(nonatomic,copy)NSString *icon;
    @property(nonatomic,copy)NSString *price;
    @property(nonatomic,copy)NSString *title;
    YYinitH(tg)
    @end

    YYtg.m文件
    代码如下:

    //
    //  YYtg.m
    //  01-团购数据显示(没有配套的类)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYtg.h"

    @implementation YYtg
    YYinitM(tg)
    @end

    主控制器

    YYViewController.m文件
    代码如下:

    //
    //  YYViewController.m
    //  01-团购数据显示(没有配套的类)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYViewController.h"
    #import "YYtg.h"

    @interface YYViewController ()<UITableViewDataSource>
    @property(nonatomic,strong)NSArray *tg;
    @property (strong, nonatomic) IBOutlet UITableView *tableview;

    @end

    代码如下:

    @implementation YYViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.tableview.rowHeight=100;
       
    }

    #pragma mark-  懒加载
    -(NSArray *)tg
    {
        if (_tg==nil) {
            NSString *fullpath=[[NSBundle mainBundle]pathForResource:@"tgs.plist" ofType:nil];
            NSArray *temparray=[NSArray arrayWithContentsOfFile:fullpath];
           
            NSMutableArray *arrayM=[NSMutableArray arrayWithCapacity:temparray.count];
            for (NSDictionary *dict in temparray) {
                YYtg *tg=[YYtg tgWithDict:dict];
                [arrayM addObject:tg];
            }
            _tg=[arrayM mutableCopy];
        }
        return _tg;
    }

    #pragma mark-数据显示
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.tg.count;
    }
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //读取xib中的数据
    //    NSArray *arrayM=[[NSBundle mainBundle]loadNibNamed:@"tgcell" owner:nil options:nil];
    //    UITableViewCell *cell=[arrayM firstObject];
        static NSString *identifier=@"tg";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
           // cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell= [[[NSBundle mainBundle]loadNibNamed:@"tgcell" owner:nil options:nil] firstObject];
        }
       
        YYtg *tg=self.tg[indexPath.row];
        //设置数据
        //使用tag
        UIImageView *imgv=(UIImageView *)[cell viewWithTag:1];
        imgv.image=[UIImage imageNamed:tg.icon];
        UILabel *buyCount=(UILabel *)[cell viewWithTag:4];
        buyCount.text=[NSString stringWithFormat:@"已有%@人购买",tg.buyCount];
        UILabel *title=(UILabel *)[cell viewWithTag:2];
        title.text=tg.title;
        UILabel *price=(UILabel *)[cell viewWithTag:3];
        price.text=[NSString stringWithFormat:@"$%@",tg.price];
       
       
        //返回cell
        return cell;
    }

    //隐藏状态栏
    -(BOOL)prefersStatusBarHidden
    {
        return YES;
    }
    @end

    使用xib自定义的UItableviewcell

    代码分析:

    上面的代码通过使用xib文件中各个控件的tag值,完成对每个部分数据的赋值和刷新。但是,作为主控制器,它应该知道xib文件中各个控件的tag值,它知道的是不是太多了呢?

    为了解决上面的问题,我们可以为自定义的cell设置一个配套的类,让这个类来操作这个xib,对外提供接口,至于内部的数据处理,外界不需要关心,也不用关心。

    改造后的代码如下:

    2.使用xib和对应的类完成自定义cell的数据展示

    新建一个类,用来管理对应的xib文件

    注意类的继承类,并把该类和xib文件进行关联

    YYtgcell.h文件代码:
    代码如下:

    //
    //  YYtgcell.h
    //  02-团购(使用xib和类完成数据展示)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import <UIKit/UIKit.h>
    #import "YYtg.h"

    @interface YYtgcell : UITableViewCell
    @property(nonatomic,strong)YYtg *yytg;

    @end

    YYtgcell.m文件
    代码如下:

    //
    //  YYtgcell.m
    //  02-团购(使用xib和类完成数据展示)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYtgcell.h"
    //私有扩展
    @interface YYtgcell()
    @property (strong, nonatomic) IBOutlet UIImageView *img;
    @property (strong, nonatomic) IBOutlet UILabel *titlelab;
    @property (strong, nonatomic) IBOutlet UILabel *pricelab;
    @property (strong, nonatomic) IBOutlet UILabel *buycountlab;
    @end

    代码如下:

    @implementation YYtgcell

    #pragma mark 重写set方法,完成数据的赋值操作
    -(void)setYytg:(YYtg *)yytg
    {
        _yytg=yytg;
        self.img.image=[UIImage imageNamed:yytg.icon];
        self.titlelab.text=yytg.title;
        self.pricelab.text=[NSString stringWithFormat:@"$%@",yytg.price];
        self.buycountlab.text=[NSString stringWithFormat:@"已有%@人购买",yytg.buyCount];
    }
    @end

    主控制器

    YYViewController.m文件
    代码如下:

    //
    //  YYViewController.m
    //  02-团购(使用xib和类完成数据展示)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYViewController.h"
    #import "YYtg.h"
    #import "YYtgcell.h"

    @interface YYViewController ()<UITableViewDataSource,UITableViewDelegate>
    @property (strong, nonatomic) IBOutlet UITableView *tableview;

    @property(strong,nonatomic)NSArray *tg;
    @end

    代码如下:

    @implementation YYViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.tableview.rowHeight=80.f;
    }
    #pragma mark-  懒加载
    -(NSArray *)tg
    {
        if (_tg==nil) {
            NSString *fullpath=[[NSBundle mainBundle]pathForResource:@"tgs.plist" ofType:nil];
            NSArray *temparray=[NSArray arrayWithContentsOfFile:fullpath];
           
            NSMutableArray *arrayM=[NSMutableArray arrayWithCapacity:temparray.count];
            for (NSDictionary *dict in temparray) {
                YYtg *tg=[YYtg tgWithDict:dict];
                [arrayM addObject:tg];
            }
            _tg=[arrayM mutableCopy];
        }
        return _tg;
    }

    #pragma mark- xib创建cell数据处理
    #pragma mark 多少组
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    #pragma mark多少行
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.tg.count;
    }
    #pragma mark设置每组每行
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *identifier= @"tg";
        YYtgcell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            //如何让创建的cell加个戳
            //对于加载的xib文件,可以到xib视图的属性选择器中进行设置
            cell=[[[NSBundle mainBundle]loadNibNamed:@"tgcell" owner:nil options:nil]firstObject];
            NSLog(@"创建了一个cell");
        }
       
        //设置cell的数据
        //获取当前行的模型
        YYtg *tg=self.tg[indexPath.row];
        cell.yytg=tg;
        return cell;
    }

    -(BOOL)prefersStatusBarHidden
    {
        return YES;
    }

    @end

    3.对上述代码进行进一步的优化和调整(MVC)

    优化如下:

    (1)把主控制器中创建cell的过程抽取到YYtgcell中完成,并对外提供一个接口。

    YYtgcell.h文件(提供接口)
    代码如下:

    #import <UIKit/UIKit.h>
    #import "YYtgModel.h"

    @interface YYtgcell : UITableViewCell
    @property(nonatomic,strong)YYtgModel *yytg;

    //把加载数据(使用xib创建cell的内部细节进行封装)
    +(instancetype)tgcellWithTableView:(UITableView *)tableView;
    @end

    YYtgcell.m文件(把创建自定义cell的部分进行封装)
    代码如下:

    //
    //  YYtgcell.m
    //  02-团购(使用xib和类完成数据展示)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYtgcell.h"
    //私有扩展
    @interface YYtgcell()
    @property (strong, nonatomic) IBOutlet UIImageView *img;
    @property (strong, nonatomic) IBOutlet UILabel *titlelab;
    @property (strong, nonatomic) IBOutlet UILabel *pricelab;
    @property (strong, nonatomic) IBOutlet UILabel *buycountlab;
    @end

    代码如下:

    @implementation YYtgcell

    #pragma mark 重写set方法,完成数据的赋值操作
    -(void)setYytg:(YYtgModel *)yytg
    {
        _yytg=yytg;
        self.img.image=[UIImage imageNamed:yytg.icon];
        self.titlelab.text=yytg.title;
        self.pricelab.text=[NSString stringWithFormat:@"$%@",yytg.price];
        self.buycountlab.text=[NSString stringWithFormat:@"已有%@人购买",yytg.buyCount];
    }

    +(instancetype)tgcellWithTableView:(UITableView *)tableView
    {
        static NSString *identifier= @"tg";
        YYtgcell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            //如何让创建的cell加个戳
            //对于加载的xib文件,可以到xib视图的属性选择器中进行设置
            cell=[[[NSBundle mainBundle]loadNibNamed:@"tgcell" owner:nil options:nil]firstObject];
            NSLog(@"创建了一个cell");
        }
        return cell;
    }

    @end

    主控器中的业务逻辑更加清晰,YYViewController.m文件代码如下
    代码如下:

    //
    //  YYViewController.m
    //  02-团购(使用xib和类完成数据展示)
    //
    //  Created by apple on 14-5-29.
    //  Copyright (c) 2014年 itcase. All rights reserved.
    //

    #import "YYViewController.h"
    #import "YYtgModel.h"
    #import "YYtgcell.h"

    @interface YYViewController ()<UITableViewDataSource,UITableViewDelegate>
    @property (strong, nonatomic) IBOutlet UITableView *tableview;

    @property(strong,nonatomic)NSArray *tg;
    @end

    代码如下:

    @implementation YYViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.tableview.rowHeight=80.f;
    }
    #pragma mark-  懒加载
    -(NSArray *)tg
    {
        if (_tg==nil) {
            NSString *fullpath=[[NSBundle mainBundle]pathForResource:@"tgs.plist" ofType:nil];
            NSArray *temparray=[NSArray arrayWithContentsOfFile:fullpath];
           
            NSMutableArray *arrayM=[NSMutableArray arrayWithCapacity:temparray.count];
            for (NSDictionary *dict in temparray) {
                YYtgModel *tg=[YYtgModel tgWithDict:dict];
                [arrayM addObject:tg];
            }
            _tg=[arrayM mutableCopy];
        }
        return _tg;
    }

    #pragma mark- xib创建cell数据处理

    #pragma mark 多少组
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }

    #pragma mark多少行
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.tg.count;
    }

    #pragma mark设置每组每行
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //1.创建cell
        YYtgcell *cell=[YYtgcell tgcellWithTableView:tableView];
      
        //2.获取当前行的模型,设置cell的数据
        YYtgModel *tg=self.tg[indexPath.row];
        cell.yytg=tg;
       
        //3.返回cell
        return cell;
    }

    #pragma mark- 隐藏状态栏
    -(BOOL)prefersStatusBarHidden
    {
        return YES;
    }

    @end

    四、推荐调整的项目文件结构

    这是调整后的文件结构,完整的MVC架构。

    注意:注意文件的命名规范。

    提示技巧:批量改名,操作如下:

    修改为想要的名称:

    实现一个简单的微博界面布局

    一、实现效果

    二、使用纯代码自定义一个tableview的步骤

    1.新建一个继承自UITableViewCell的类

    2.重写initWithStyle:reuseIdentifier:方法

    添加所有需要显示的子控件(不需要设置子控件的数据和frame,  子控件要添加到contentView中)

    进行子控件一次性的属性设置(有些属性只需要设置一次, 比如字体/固定的图片)

    3.提供2个模型

    数据模型: 存放文字数据/图片数据

    frame模型: 存放数据模型/所有子控件的frame/cell的高度

    4.cell拥有一个frame模型(不要直接拥有数据模型)

    5.重写frame模型属性的setter方法: 在这个方法中设置子控件的显示数据和frame

    6.frame模型数据的初始化已经采取懒加载的方式(每一个cell对应的frame模型数据只加载一次)

    三、文件结构和实现代码

    1.文件结构

    2.实现代码:

    NJWeibo.h文件
    代码如下:

    #import <Foundation/Foundation.h>

    @interface NJWeibo : NSObject
    @property (nonatomic, copy) NSString *text; // 内容
    @property (nonatomic, copy) NSString *icon; // 头像
    @property (nonatomic, copy) NSString *name; // 昵称
    @property (nonatomic, copy) NSString *picture; // 配图
    @property (nonatomic, assign) BOOL vip;

    - (id)initWithDict:(NSDictionary *)dict;
    + (id)weiboWithDict:(NSDictionary *)dict;
    @end

    NJWeibo.m文件
    代码如下:

    #import "NJWeibo.h"

    @implementation NJWeibo

    - (id)initWithDict:(NSDictionary *)dict
    {
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dict];
        }
        return self;
    }

    + (id)weiboWithDict:(NSDictionary *)dict
    {
        return [[self alloc] initWithDict:dict];
    }

    @end

    NJWeiboCell.h文件
    代码如下:

    #import <UIKit/UIKit.h>
    @class NJWeiboFrame;

    @interface NJWeiboCell : UITableViewCell
    /**
     *  接收外界传入的模型
     */
    //@property (nonatomic, strong) NJWeibo *weibo;

    @property (nonatomic, strong) NJWeiboFrame *weiboFrame;

    + (instancetype)cellWithTableView:(UITableView *)tableView;
    @end

    NJWeiboCell.m文件
    代码如下:

    #import "NJWeiboCell.h"
    #import "NJWeibo.h"
    #import "NJWeiboFrame.h"

    #define NJNameFont [UIFont systemFontOfSize:15]
    #define NJTextFont [UIFont systemFontOfSize:16]

    @interface NJWeiboCell ()
    /**
     *  头像
     */
    @property (nonatomic, weak) UIImageView *iconView;
    /**
     *  vip
     */
    @property (nonatomic, weak) UIImageView *vipView;
    /**
     *  配图
     */
    @property (nonatomic, weak) UIImageView *pictureView;
    /**
     *  昵称
     */
    @property (nonatomic, weak) UILabel *nameLabel;
    /**
     *  正文
     */
    @property (nonatomic, weak) UILabel *introLabel;
    @end

    代码如下:

    @implementation NJWeiboCell

    + (instancetype)cellWithTableView:(UITableView *)tableView
    {
        // NSLog(@"cellForRowAtIndexPath");
        static NSString *identifier = @"status";
        // 1.缓存中取
        NJWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        // 2.创建
        if (cell == nil) {
            cell = [[NJWeiboCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        return cell;
    }

    /**
     *  构造方法(在初始化对象的时候会调用)
     *  一般在这个方法中添加需要显示的子控件
     */
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            // 让自定义Cell和系统的cell一样, 一创建出来就拥有一些子控件提供给我们使用
            // 1.创建头像
            UIImageView *iconView = [[UIImageView alloc] init];
            [self.contentView addSubview:iconView];
            self.iconView = iconView;
           
            // 2.创建昵称
            UILabel *nameLabel = [[UILabel alloc] init];
            nameLabel.font = NJNameFont;
            // nameLabel.backgroundColor = [UIColor redColor];
            [self.contentView addSubview:nameLabel];
            self.nameLabel = nameLabel;
           
            // 3.创建vip
            UIImageView *vipView = [[UIImageView alloc] init];
            vipView.image = [UIImage imageNamed:@"vip"];
            [self.contentView addSubview:vipView];
            self.vipView = vipView;
           
            // 4.创建正文
            UILabel *introLabel = [[UILabel alloc] init];
            introLabel.font = NJTextFont;
            introLabel.numberOfLines = 0;
            // introLabel.backgroundColor = [UIColor greenColor];
            [self.contentView addSubview:introLabel];
            self.introLabel = introLabel;
           
            // 5.创建配图
            UIImageView *pictureView = [[UIImageView alloc] init];
            [self.contentView addSubview:pictureView];
            self.pictureView = pictureView;
           
        }
        return self;
    }

    - (void)setWeiboFrame:(NJWeiboFrame *)weiboFrame
    {
        _weiboFrame = weiboFrame;
       
        // 1.给子控件赋值数据
        [self settingData];
        // 2.设置frame
        [self settingFrame];
    }

    /**
     *  设置子控件的数据
     */
    - (void)settingData
    {
        NJWeibo *weibo = self.weiboFrame.weibo;
       
        // 设置头像
        self.iconView.image = [UIImage imageNamed:weibo.icon];
        // 设置昵称
        self.nameLabel.text = weibo.name;
        // 设置vip
        if (weibo.vip) {
            self.vipView.hidden = NO;
            self.nameLabel.textColor = [UIColor redColor];
        }else
        {
            self.vipView.hidden = YES;
            self.nameLabel.textColor = [UIColor blackColor];
        }
        // 设置内容
        self.introLabel.text = weibo.text;
       
        // 设置配图
        if (weibo.picture) {// 有配图
            self.pictureView.image = [UIImage imageNamed:weibo.picture];
            self.pictureView.hidden = NO;
        }else
        {
            self.pictureView.hidden = YES;
        }
    }
    /**
     *  设置子控件的frame
     */
    - (void)settingFrame
    {

           // 设置头像的frame
        self.iconView.frame = self.weiboFrame.iconF;
       
        // 设置昵称的frame
            self.nameLabel.frame = self.weiboFrame.nameF;
       
        // 设置vip的frame
           self.vipView.frame = self.weiboFrame.vipF;
       
        // 设置正文的frame
           self.introLabel.frame = self.weiboFrame.introF;
       
        // 设置配图的frame

        if (self.weiboFrame.weibo.picture) {// 有配图
            self.pictureView.frame = self.weiboFrame.pictrueF;
        }
    }

    /**
     *  计算文本的宽高
     *
     *  @param str     需要计算的文本
     *  @param font    文本显示的字体
     *  @param maxSize 文本显示的范围
     *
     *  @return 文本占用的真实宽高
     */
    - (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
    {
        NSDictionary *dict = @{NSFontAttributeName : font};
        // 如果将来计算的文字的范围超出了指定的范围,返回的就是指定的范围
        // 如果将来计算的文字的范围小于指定的范围, 返回的就是真实的范围
        CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
        return size;
    }

    @end

    NJWeiboFrame.h文件
    代码如下:

    //  专门用来保存每一行数据的frame, 计算frame

    #import <Foundation/Foundation.h>
    @class NJWeibo;
    @interface NJWeiboFrame : NSObject
    /**
     *  头像的frame
     */
    @property (nonatomic, assign) CGRect iconF;
    /**
     *  昵称的frame
     */
    @property (nonatomic, assign) CGRect nameF;
    /**
     *  vip的frame
     */
    @property (nonatomic, assign) CGRect vipF;
    /**
     *  正文的frame
     */
    @property (nonatomic, assign) CGRect introF;
    /**
     *  配图的frame
     */
    @property (nonatomic, assign) CGRect pictrueF;
    /**
     *  行高
     */
    @property (nonatomic, assign) CGFloat cellHeight;

    /**
     *  模型数据
     */
    @property (nonatomic, strong) NJWeibo *weibo;
    @end

    NJWeiboFrame.m文件
    代码如下:

    #import "NJWeiboFrame.h"
    #import "NJWeibo.h"
    #define NJNameFont [UIFont systemFontOfSize:15]
    #define NJTextFont [UIFont systemFontOfSize:16]

    @implementation NJWeiboFrame

    - (void)setWeibo:(NJWeibo *)weibo
    {
        _weibo = weibo;
       
        // 间隙
        CGFloat padding = 10;
       
        // 设置头像的frame
        CGFloat iconViewX = padding;
        CGFloat iconViewY = padding;
        CGFloat iconViewW = 30;
        CGFloat iconViewH = 30;
        self.iconF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);
       
        // 设置昵称的frame
        // 昵称的x = 头像最大的x + 间隙
        CGFloat nameLabelX = CGRectGetMaxX(self.iconF) + padding;
        // 计算文字的宽高
        CGSize nameSize = [self sizeWithString:_weibo.name font:NJNameFont maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
       
        CGFloat nameLabelH = nameSize.height;
        CGFloat nameLabelW = nameSize.width;
        CGFloat nameLabelY = iconViewY + (iconViewH - nameLabelH) * 0.5;
       self.nameF = CGRectMake(nameLabelX, nameLabelY, nameLabelW, nameLabelH);
       
        // 设置vip的frame
        CGFloat vipViewX = CGRectGetMaxX(self.nameF) + padding;
        CGFloat vipViewY = nameLabelY;
        CGFloat vipViewW = 14;
        CGFloat vipViewH = 14;
        self.vipF = CGRectMake(vipViewX, vipViewY, vipViewW, vipViewH);
       
        // 设置正文的frame
        CGFloat introLabelX = iconViewX;
        CGFloat introLabelY = CGRectGetMaxY(self.iconF) + padding;
        CGSize textSize =  [self sizeWithString:_weibo.text font:NJTextFont maxSize:CGSizeMake(300, MAXFLOAT)];
       
        CGFloat introLabelW = textSize.width;
        CGFloat introLabelH = textSize.height;
       
        self.introF = CGRectMake(introLabelX, introLabelY, introLabelW, introLabelH);
       
        // 设置配图的frame
        CGFloat cellHeight = 0;
        if (_weibo.picture) {// 有配图
            CGFloat pictureViewX = iconViewX;
            CGFloat pictureViewY = CGRectGetMaxY(self.introF) + padding;
            CGFloat pictureViewW = 100;
            CGFloat pictureViewH = 100;
            self.pictrueF = CGRectMake(pictureViewX, pictureViewY, pictureViewW, pictureViewH);
           
            // 计算行高
            self.cellHeight = CGRectGetMaxY(self.pictrueF) + padding;
        }else
        {
            // 没有配图情况下的行高
            self.cellHeight = CGRectGetMaxY(self.introF) + padding;
        }
       
    }

    /**
     *  计算文本的宽高
     *
     *  @param str     需要计算的文本
     *  @param font    文本显示的字体
     *  @param maxSize 文本显示的范围
     *
     *  @return 文本占用的真实宽高
     */
    - (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
    {
        NSDictionary *dict = @{NSFontAttributeName : font};
        // 如果将来计算的文字的范围超出了指定的范围,返回的就是指定的范围
        // 如果将来计算的文字的范围小于指定的范围, 返回的就是真实的范围
        CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
        return size;
    }
    @end

    主控制器

    NJViewController.m文件
    代码如下:

    #import "NJViewController.h"
    #import "NJWeibo.h"
    #import "NJWeiboCell.h"
    #import "NJWeiboFrame.h"

    @interface NJViewController ()
    @property (nonatomic, strong) NSArray *statusFrames;
    @end

    代码如下:

    @implementation NJViewController

    #pragma mark - 数据源方法

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.statusFrames.count;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NJWeiboCell *cell = [NJWeiboCell cellWithTableView:tableView];
        // 3.设置数据
       cell.weiboFrame = self.statusFrames[indexPath.row];
       
        // 4.返回
        return cell;
    }
    #pragma mark - 懒加载
    - (NSArray *)statusFrames
    {
        if (_statusFrames == nil) {
            NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"statuses.plist" ofType:nil];
            NSArray *dictArray = [NSArray arrayWithContentsOfFile:fullPath];
            NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];
            for (NSDictionary *dict in dictArray) {
                // 创建模型
                NJWeibo *weibo = [NJWeibo weiboWithDict:dict];
                // 根据模型数据创建frame模型
                NJWeiboFrame *wbF = [[NJWeiboFrame alloc] init];
                wbF.weibo = weibo;
               
                [models addObject:wbF];
            }
            self.statusFrames = [models copy];
        }
        return _statusFrames;
    }

    #pragma mark - 代理方法
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // NSLog(@"heightForRowAtIndexPath");
        // 取出对应航的frame模型
        NJWeiboFrame *wbF = self.statusFrames[indexPath.row];
        NSLog(@"height = %f", wbF.cellHeight);
        return wbF.cellHeight;
    }

    - (BOOL) prefersStatusBarHidden
    {
        return YES;
    }
    @end

    四、补充说明

    由于系统提供的tableview可能并不能满足我们的开发需求,所以经常要求我们能够自定义tableview。

    自定义tableview有两种方式,一种是使用xib创建,一种是使用纯代码的方式创建。

    对于样式一样的tableview,通常使用xib进行创建,对于高度不一样,内容也不完全一致的通常使用纯代码进行自定义。

    一起学吧部分文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与一起学吧进行文章共享合作。

    广告
    广告
    广告