OC开发_代码片段——代码编写自定义的tableViewCell

时间:2022-07-18 04:39:23

一、介绍

之前已经实现过通过简单的XIB文件来自定义我们的tableViewCell,包括每一步的步骤和代码:http://www.cnblogs.com/daomul/p/4355999.html

现在我们采取另外一种方式,通过纯编写代码来实现自定义我们的tableview,那么什么时候使用XIB,是这样的,当我们的cell的高度是固定的时候,我们可以采用XIB文件,如果我们的cell高度是不固定的,那么就需要使用代码编写了

二、效果

话不多说,上一个没有放图,这个先看我们大概做出来的效果如下:

OC开发_代码片段——代码编写自定义的tableViewCell

三、 实现步骤

四、代码清单

ViewController.m:

 //
// ViewController.m
// codeDefinedForTableviewcell
//
// Created by bos on 15-3-22.
// Copyright (c) 2015年 axiba. All rights reserved.
// #import "ViewController.h"
#import "weiboCell.h"
#import "Weibo.h"
#import "WeiboFrame.h" @interface ViewController ()
{
//全局变量,对应着从文件中取得的数据
//NSMutableArray *_weibos;
NSMutableArray *_weiboFrames;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //从plist文件中加载数据数组
NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data.plist" ofType:nil]]; //遍历添加到我们的微博模型中
_weiboFrames = [NSMutableArray array];
for (NSDictionary *dict in arr) {
WeiboFrame *wframe = [[WeiboFrame alloc]init];
wframe.weibo = [Weibo weiboWithDict:dict]; [_weiboFrames addObject:wframe];
}
/*_weibos = [NSMutableArray array];
for (NSDictionary *key in arr) { //每一个可变数组中存放每条模型(多少条就是对应着多少行 )
[_weibos addObject:[Weibo weiboWithDict:key]];
}*/
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _weiboFrames.count;
} -(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1、去缓存池取出cell
weiboCell *cell = [tableView dequeueReusableCellWithIdentifier:[weiboCell getID]]; //2、如果不存在缓存,则创建一个
if (cell ==nil) {
cell = [[weiboCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[weiboCell getID]];
} //3、传递模型数据(相当于setWeibo,没有传递则)
//WeiboFrame *wframe = [[WeiboFrame alloc] init];
//wframe.weibo = _weiboFrames[indexPath.row];
cell.weiboframe = _weiboFrames[indexPath.row]; return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//WeiboFrame *wframe = [[WeiboFrame alloc] init];
//wframe.weibo = _weibofr[indexPath.row];
//return wframe.cellHeight; return [_weiboFrames[indexPath.row] cellHeight];
} @end

WeiboCell.h

 //
// weiboCell.h
// codeDefinedForTableviewcell
//
// Created by bos on 15-3-22.
// Copyright (c) 2015年 axiba. All rights reserved.
// #import <UIKit/UIKit.h>
@class WeiboFrame; @interface weiboCell : UITableViewCell @property (nonatomic,strong) UILabel *iconlabel;
@property (nonatomic,strong) UILabel *namelabel;
@property (nonatomic ,strong) UILabel *timelabel;
@property (nonatomic,strong) UIImageView *vipImage;
@property (nonatomic,strong) UIImageView *picImage;
@property (nonatomic,strong) UILabel *contentLabel;
@property (nonatomic,strong) UILabel *from; @property (nonatomic,strong) WeiboFrame *weiboframe; +(NSString *)getID;
@end

WeiboCell.m

 //
// weiboCell.m 模型显示到我们的cell里面
// codeDefinedForTableviewcell
//
// Created by bos on 15-3-22.
// Copyright (c) 2015年 axiba. All rights reserved.
// #import "weiboCell.h"
#import "Weibo.h"
#import "WeiboFrame.h" #define kCellBorder 10
#define kIconWH 40 @interface weiboCell()
{
UIImageView *_icon;
UILabel *_name;
UILabel *_content;
UIImageView *_vip;
UIImageView *_pic;
UILabel *_from;
UILabel *_time;
} @end @implementation weiboCell -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) { //不清楚高度则先添加基本得内部所有子控件
[self setData];
} return self;
} #pragma 设置微博数据以及高度frame
-(void)setWeiboframe:(WeiboFrame *)weiboframe
{
//1.将weibo负值给我们的weibo模型
_weiboframe = weiboframe; //2.设置微博数据
[self settingWeiboData]; //3.设置子控件的frame
[self settingWeiboFrame];
}
#pragma 设置微博数据
-(void)settingWeiboData
{
Weibo *weibo = _weiboframe.weibo;
//赋值
_icon.image = [UIImage imageNamed:weibo.icon]; _name.text = weibo.name; _content.text = weibo.content;
_content.numberOfLines = ; _from.text = weibo.from; _vip.hidden = !weibo.vip; _time.text = weibo.time; // 配图
if (weibo.pic) {
_pic.hidden = NO;
_pic.image = [UIImage imageNamed:weibo.pic];
}else
{
_pic.hidden = YES;
} }
#pragma 设置微博高度frame
-(void) settingWeiboFrame
{ //1、头像
_icon.frame = _weiboframe.iconFrame; //2、昵称
_name.frame = _weiboframe.nameFrame; //3VIP图标
_vip.frame = _weiboframe.vipFrame; //4、时间
_time.frame = _weiboframe.timeFrame; //5来源
_from.frame = _weiboframe.fromFrame; //6正文
_content.frame = _weiboframe.contentFrame; //7配图
if (_weiboframe.weibo.pic) { _pic.frame = _weiboframe.picFrame;
}
} #pragma 添加基本的内部控件
-(void)setData
{
//1、头像
_icon = [[UIImageView alloc] init];
[self.contentView addSubview:_icon]; //2、会员姓名
_name = [[UILabel alloc] init];
[self.contentView addSubview: _name]; //3、时间
_time = [[UILabel alloc] init];
_time.font = [UIFont systemFontOfSize:];
[self.contentView addSubview:_time]; //4、正文
_content= [[UILabel alloc] init];
[self.contentView addSubview:_content]; //5、VIP图标
_vip = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"vip.png"]];
[self.contentView addSubview:_vip]; //6、微博配图
_pic= [[UIImageView alloc] init];
[self.contentView addSubview:_pic]; //7、来源
_from = [[UILabel alloc] init];
_from.font = _time.font;
[self.contentView addSubview:_from]; } +(NSString *)getID
{
return @"cell";
} @end

Weibo.h

 //
// Weibo.h
// codeDefinedForTableviewcell
//
// Created by bos on 15-3-22.
// Copyright (c) 2015年 axiba. All rights reserved.
// #import <Foundation/Foundation.h> @interface Weibo : NSObject @property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *icon;
@property (nonatomic,copy) NSString *time;
@property (nonatomic, copy) NSString *pic;
@property (nonatomic,copy) NSString *content;
@property (nonatomic,copy) NSString *from;
@property (nonatomic,assign) BOOL vip; -(id) initWithDict:(NSDictionary *)dict;
+(id) weiboWithDict:(NSDictionary *)dict; @end

Weibo.m

 //
// Weibo.m 模型
// codeDefinedForTableviewcell
//
// Created by bos on 15-3-22.
// Copyright (c) 2015年 axiba. All rights reserved.
// #import "Weibo.h" @implementation Weibo -(id) initWithDict:(NSDictionary *)dict
{
if (self == [super init]) {
self.name =dict[@"name"];
self.icon = dict[@"icon"];
self.time = dict[@"time"];
self.content = dict[@"desc"];
self.from = dict[@"from"];
self.pic = dict[@"pic"];
self.vip = [dict[@"vip"] boolValue];
}
return self;
} //必须实现的类方法,否则类无法alloc 自己(self)
+(id) weiboWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
} @end

WeiboFrame.h

 //
// WeiboFrame.h
// codeDefinedForTableviewcell
//
// Created by bos on 15-4-8.
// Copyright (c) 2015年 axiba. All rights reserved.
// 用来存放某一个cell内部所有的子控件 的frame #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> @class Weibo;
@interface WeiboFrame : NSObject // 头像 的frame
@property (nonatomic,assign,readonly) CGRect iconFrame;
// 是不是大V 的frame
@property (nonatomic,assign,readonly) CGRect vipFrame;
// 名字 的frame
@property (nonatomic,assign,readonly) CGRect nameFrame;
// 发表时间 的frame
@property (nonatomic,assign,readonly) CGRect timeFrame;
// 正文内容 的frame
@property (nonatomic,assign,readonly) CGRect contentFrame;
// 大图片 的frame
@property (nonatomic,assign,readonly) CGRect picFrame;
// 来自客户端 的frame
@property (nonatomic,assign,readonly) CGRect fromFrame; @property (nonatomic,assign,readonly) CGFloat cellHeight;
@property (nonatomic,strong) Weibo *weibo; @end

WeiboFram.m

 //
// WeiboFrame.m
// codeDefinedForTableviewcell
//
// Created by bos on 15-4-8.
// Copyright (c) 2015年 axiba. All rights reserved.
// yonglai #define kCellBorder 10
#define kIconWH 40 #import "WeiboFrame.h"
#import "Weibo.h" @implementation WeiboFrame -(void) setWeibo:(Weibo *)weibo
{
_weibo = weibo; //1、头像
CGFloat iconX = kCellBorder;
CGFloat iconY = kCellBorder;
_iconFrame = CGRectMake(iconX, iconY, kIconWH, kIconWH); //2、昵称
CGFloat nameX = CGRectGetMaxX(_iconFrame) + kCellBorder;
CGFloat nameY = iconY;
//宽高取决于文字宽度
CGSize nameSize = [self getLabelHeighDynamic:_weibo.name];
_nameFrame = CGRectMake(nameX, nameY, nameSize.width, nameSize.height); //3VIP图标 CGFloat vipX = CGRectGetMaxX(_nameFrame) + kCellBorder;
CGFloat vipY = nameY;
_vipFrame = CGRectMake(vipX, vipY, , ); //4、时间
CGFloat timeX = nameX;
CGFloat timeY = CGRectGetMaxY(_nameFrame) + kCellBorder;
CGSize timeSize = [self getLabelHeighDynamic:_weibo.time];
_timeFrame = CGRectMake(timeX, timeY, timeSize.width, timeSize.height); //5来源
CGFloat fromX = CGRectGetMaxX(_timeFrame) +kCellBorder;
CGFloat fromY = timeY;
CGSize fromSize = [self getLabelHeighDynamic: _weibo.from];
_fromFrame = CGRectMake(fromX, fromY, fromSize.width, fromSize.height); //6正文
CGFloat contentX = iconX;
CGFloat contentY = MAX(CGRectGetMaxY(_iconFrame), CGRectGetMaxY(_timeFrame));
CGRect contentSize = [self getContentFrameDynamic: _weibo.content];
_contentFrame = CGRectMake(contentX, contentY, contentSize.size.width, contentSize.size.height); //7配图
if (_weibo.pic.length > ) { CGFloat picX = contentX;
CGFloat picY = CGRectGetMaxY(_contentFrame) +kCellBorder;
_picFrame = CGRectMake(picX, picY, , ); _cellHeight = CGRectGetMaxY(_picFrame) + kCellBorder;
}
else
{
_cellHeight = CGRectGetMaxY(_contentFrame) +kCellBorder;
}
} #pragma 根据文字长度动态确定label的高度
-(CGSize)getLabelHeighDynamic:(NSString *)word
{
UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:18.0f];
CGSize size = [word sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
return size;
} #pragma 根据正文内容多少,动态确定正文content的frame -(CGRect)getContentFrameDynamic:(NSString *)word
{
// 宽度W
CGFloat contentW = - *kCellBorder;
// label的字体 HelveticaNeue Courier
UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:18.0f];
//_content.font = fnt; //_content.lineBreakMode = NSLineBreakByWordWrapping;
// iOS7中用以下方法替代过时的iOS6中的sizeWithFont:constrainedToSize:lineBreakMode:方法
CGRect tmpRect = [word boundingRectWithSize:CGSizeMake(contentW, ) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil] context:nil]; return tmpRect; } @end

五、遇到的问题总结

1、number函数写错, 记得是tableview先写,否则导致无法执行cellforRowAtIndexpath无法执行

2、忘记传递模型数据,导致set方法没有执行

3、IOS7中用以下方法

- (CGSize)sizeWithAttributes:(NSDictionary *)attrs;

替代过时的iOS6中的- (CGSize)sizeWithFont:(UIFont *)font 方法

4、如果头文件中遇到类似于“编绎显示Unknown type name “CGFloat”  错误解决方法”

直接加头文件:

#import <UIKit/UIKit.h>或者将Compile Sources As 改为 Objective-C++

5、在ViewDidLoad使用以下方法在取缓存池的值的时候,可以不用判断是否为空,会自动取缓冲取值,适用于6.0+

[self.tableView registerClass:[Mycell class] forCellReuseIdenifier:@"cellID"];

六、源代码下载地址:

http://pan.baidu.com/s/1kTqsTpH