源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

全面解析iOS应用中自定义UITableViewCell的方法

  • 时间:2021-09-24 21:50 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:全面解析iOS应用中自定义UITableViewCell的方法
有时候我们需要自己定义UITableViewCell的风格,其实就是向行中添加子视图。添加子视图的方法主要有两种:使用代码以及从.xib文件加载。当然后一种方法比较直观。 [b]一、基本用法 [/b]我们这次要自定义一个Cell,使得它像QQ好友列表的一行一样:左边是一张图片,图片的右边是三行标签: [img]http://files.jb51.net/file_images/article/201604/20164992950112.png?20163993041[/img] 当然,我们不会搞得这么复杂,只是有点意思就行。 1、运行Xcode 4.2,新建一个Single View Application,名称为Custom Cell: [img]http://files.jb51.net/file_images/article/201604/20164993051610.png?2016399310[/img] 2、将图片资源导入到工程。为此,我找了14张50×50的.png图片,名称依次是1、2、……、14,放在一个名为Images的文件夹中。将此文件夹拖到工程中,在弹出的窗口中选中Copy items into… [img]http://files.jb51.net/file_images/article/201604/20164993110344.png?20163993117[/img] 添加完成后,工程目录如下: [img]http://files.jb51.net/file_images/article/201604/20164993126002.png?20163993135[/img] 3、创建一个UITableViewCell的子类:选中Custom Cell目录,依次选择File — New — New File,在弹出的窗口,左边选择Cocoa Touch,右边选择Objective-C class: [img]http://files.jb51.net/file_images/article/201604/20164993147213.png?20163993158[/img] 单击Next,输入类名CustomCell,Subclass of选择UITableViewCell: [img]http://files.jb51.net/file_images/article/201604/20164993206913.png?20163993214[/img] 之后选择Next和Create,就建立了两个文件:CustomCell.h和CustomCell.m。 4、创建CustomCell.xib:依次选择File — New — New File,在弹出的窗口,左边选择User Interface,右边选择Empty: [img]http://files.jb51.net/file_images/article/201604/20164993227183.png?20163993236[/img] 单击Next,选择iPhone,再单击Next,输入名称为CustomCell,选择好位置: [img]http://files.jb51.net/file_images/article/201604/20164993247395.png?20163993255[/img] 单击Create,这样就创建了CustomCell.xib。 5、打开CustomCell.xib,拖一个Table View Cell控件到面板上: [img]http://files.jb51.net/file_images/article/201604/20164993306795.png?20163993316[/img] 选中新加的控件,打开Identity Inspector,选择Class为CustomCell;然后打开Size Inspector,调整高度为60。 6、向新加的Table View Cell添加控件:拖放一个ImageView控件到左边,并设置大小为50×50。然后在ImageView右边添加三个Label,设置标签字号,最上边的是14,其余两个是12: [img]http://files.jb51.net/file_images/article/201604/20164993327862.png?20163993337[/img] 接下来向CustomCell.h添加Outlet映射,将ImageView与三个Label建立映射,名称分别为imageView、nameLabel、decLabel以及locLable,分别表示头像、昵称、个性签名,地点。 选中Table View Cell,打开Attribute Inspector,将Identifier设置为CustomCellIdentifier: [img]http://files.jb51.net/file_images/article/201604/20164993346980.png?20163993356[/img] 为了充分使用这些标签,还要自己创建一些数据,存在plist文件中,后边会做。 7、打开CustomCell.h,添加属性:
[u]复制代码[/u] 代码如下:
@property (copy, nonatomic) UIImage *image; @property (copy, nonatomic) NSString *name; @property (copy, nonatomic) NSString *dec; @property (copy, nonatomic) NSString *loc;
8、打开CustomCell.m,向其中添加代码: 8.1 在@implementation下面添加代码:
[u]复制代码[/u] 代码如下:
@synthesize image; @synthesize name; @synthesize dec; @synthesize loc;
8.2 在@end之前添加代码:
[u]复制代码[/u] 代码如下:
- (void)setImage:(UIImage *)img {     if (![img isEqual:image]) {         image = [img copy];         self.imageView.image = image;     } } -(void)setName:(NSString *)n {     if (![n isEqualToString:name]) {         name = [n copy];         self.nameLabel.text = name;     } } -(void)setDec:(NSString *)d {     if (![d isEqualToString:dec]) {         dec = [d copy];         self.decLabel.text = dec;     } } -(void)setLoc:(NSString *)l {     if (![l isEqualToString:loc]) {         loc = [l copy];         self.locLabel.text = loc;     } }
这相当于重写了各个set函数,从而当执行赋值操作时,会执行我们自己写的函数。 好了,现在自己定义的Cell已经可以使用了。 不过在此之前,我们先新建一个plist,用于存储想要显示的数据。建立plist文件的方法前面的文章有提到。我们建好一个friendsInfo.plist,往其中添加数据如下: [img]http://files.jb51.net/file_images/article/201604/20164993418241.png?20163993428[/img] 注意每个节点类型选择。 9、打开ViewController.xib,拖一个Table View到视图上,并将Delegate和DataSource都指向File' Owner,就像上一篇文章介绍的一样。 10、打开ViewController.h,向其中添加代码:
[u]复制代码[/u] 代码如下:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> @property (strong, nonatomic) NSArray *dataList; @property (strong, nonatomic) NSArray *imageList; @end
11、打开ViewController.m,添加代码: 11.1 在首部添加:
[u]复制代码[/u] 代码如下:
#import "CustomCell.h"
11.2 在@implementation后面添加代码:
[u]复制代码[/u] 代码如下:
@synthesize dataList; @synthesize imageList;
11.3 在viewDidLoad方法中添加代码:
[u]复制代码[/u] 代码如下:
- (void)viewDidLoad {     [super viewDidLoad];     // Do any additional setup after loading the view, typically from a nib.     //加载plist文件的数据和图片     NSBundle *bundle = [NSBundle mainBundle];     NSURL *plistURL = [bundle URLForResource:@"friendsInfo" withExtension:@"plist"];         NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];         NSMutableArray *tmpDataArray = [[NSMutableArray alloc] init];     NSMutableArray *tmpImageArray = [[NSMutableArray alloc] init];     for (int i=0; i<[dictionary count]; i++) {         NSString *key = [[NSString alloc] initWithFormat:@"%i", i+1];         NSDictionary *tmpDic = [dictionary objectForKey:key];         [tmpDataArray addObject:tmpDic];                 NSString *imageUrl = [[NSString alloc] initWithFormat:@"%i.png", i+1];         UIImage *image = [UIImage imageNamed:imageUrl];         [tmpImageArray addObject:image];     }     self.dataList = [tmpDataArray copy];     self.imageList = [tmpImageArray copy]; }
11.4 在ViewDidUnload方法中添加代码:
[u]复制代码[/u] 代码如下:
self.dataList = nil; self.imageList = nil;
11.5 在@end之前添加代码:
[u]复制代码[/u] 代码如下:
#pragma mark - #pragma mark Table Data Source Methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {     return [self.dataList count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     static NSString *CustomCellIdentifier = @"CustomCellIdentifier";         static BOOL nibsRegistered = NO;     if (!nibsRegistered) {         UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];         [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];         nibsRegistered = YES;     }         CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];           NSUInteger row = [indexPath row];     NSDictionary *rowData = [self.dataList objectAtIndex:row];         cell.name = [rowData objectForKey:@"name"];     cell.dec = [rowData objectForKey:@"dec"];     cell.loc = [rowData objectForKey:@"loc"];     cell.image = [imageList objectAtIndex:row];          return cell; } #pragma mark Table Delegate Methods - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {     return 60.0; } - (NSIndexPath *)tableView:(UITableView *)tableView   willSelectRowAtIndexPath:(NSIndexPath *)indexPath {     return nil; }
12、运行: [img]http://files.jb51.net/file_images/article/201604/20164993439292.jpg?20163993450[/img] [b]二、如何重用UITableviewCell[/b] 重用的目的是为了减少内存消耗,假如有1千个cell,如果不重用,那么每一次滑动都得重新 alloc 很多很多的cell,耗费内存,同时屏幕会出现不连续的现象,晃眼睛。 重用cell很简单,在创建cell的时候,使用 alloc initwithtableviewCellStyle:reuseIdentifer这个接口创建cell实例,而非使用alloc initwithFrame 使用前者表示该cell可重用,identifer使用一个固定的NSString即可 代码如下:
[u]复制代码[/u] 代码如下:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {      static NSString *CellIdentifier = @"Cell";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];//首先从可重用队列里面弹出一个cell      if (cell == nil) {//说明可重用队列里面并cell,此时需要重新创建cell实例,采用下面方法          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;        }else{//此时表示有可重用cell,直接返回即可          NSLog(@"cell 重用啦");      }          return cell;  } 
[b]三、如何如何动态调整cell的高度? [/b]这个问题还是比较头疼的,下面这个函数肯定要用到
[u]复制代码[/u] 代码如下:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
经过实践之后发现,可以在创建cell或者重用cell的时候,设置其frame 比如cell.frame=CGRectMake(0,0,320,450); 这个代码会有效,同时在下面这个函数里面 使用:
[u]复制代码[/u] 代码如下:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  {          NSLog(@"当前是第%ld行",(long)indexPath.row);            UITableViewCell *myCell=[self tableView:tableView cellForRowAtIndexPath:indexPath];//获取当前indexPath中的cell实例      if( myCell == nil ){          return 0;                }else{                    NSLog(@"%f",myCell.frame.size.height);          return  myCell.frame.size.height;                }      return 0;        } 
上面获取当前indexPath的cell实例会重新申请建立一个实例(意思是个cell实际要创建两个实例) 这样的目的是为了获取cell的frame,如果不这样做也可以在第一部分创建cell的时候,将cell的frame保存在一个私有 变量中,在heightForRowAtIndexPath中访问这个私有变量 通过上述方式可以动态改变UITableViewCell的高度 [b]四、对于一个UILabel,根据其内容计算CGRect[/b] 首先要设置UILable的font,比如 tmLabel.font=[UIFont  systemFontOfSize:14.0f]; 然后使用boundingRectOfSize计算出该尺寸对应的矩形大小,代码如下:
[u]复制代码[/u] 代码如下:
NSDictionary *attrDic=@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]};  CGSize labelSize=[text boundingRectWithSize:CGSizeMake(320, 990)                                      options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading                                   attributes:attrDic context:nil].size;    CGRect labelRect=CGRectMake(0, 0, labelSize.width, labelSize.height);
   现在UILable的rect都可以被计算出来了,那么如果自定义一个UITableViewCell,并且其内部的UILabel高度可变的话 也是可以实现的 [b]五、内部含有可变高度的UILabel的UITableViewCell [/b]如果还有其他控件,比如UIButton等等,也是一样的。 这些控件在实例化的时候,设置frame为CGRectZero, 然后分别计算各自的高度和尺寸 使用cell.contentview addSubview 的方式,将这些子空间添加到cell中。重新计算cell的frame时 也需要把这些控件的frame累加上。上代码:
[u]复制代码[/u] 代码如下:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {        static NSString *CellIdentifier = @"Cell";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];            if (cell == nil) {          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;                    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];          label.tag = 1;          label.lineBreakMode = NSLineBreakByCharWrapping;          label.highlightedTextColor = [UIColor whiteColor];          label.numberOfLines = 0;          label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制          label.font=[UIFont systemFontOfSize:12.0f];          label.backgroundColor = [UIColor grayColor];          [cell.contentView addSubview:label];                    UIButton *tmpButton=[[UIButton alloc]initWithFrame:CGRectZero];          tmpButton.tag=2;          tmpButton.backgroundColor=[UIColor cyanColor];          [cell.contentView addSubview:tmpButton];          tmpButton.opaque=NO;          [tmpButton setTitle:@"nihao" forState:UIControlStateNormal];          [tmpButton setTitleColor:[UIColor whiteColor ]forState:UIControlStateHighlighted];          [tmpButton addTarget:self action:@selector(tmpButtonHandler:) forControlEvents:UIControlEventTouchUpInside];                }else{          NSLog(@"cell 重用啦");      }                UILabel *tmpLabel=(UILabel *)[cell viewWithTag:1];          NSString *text=[tmpArray objectAtIndex:indexPath.row];          tmpLabel.text=text;                    UIButton *tmpButton=(UIButton *)[cell viewWithTag:2];                    NSDictionary *attrDic=@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]};          CGSize labelSize=[text boundingRectWithSize:CGSizeMake(320, 990)                                              options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading                                           attributes:attrDic context:nil].size;                    CGRect labelRect=CGRectMake(0, 0, labelSize.width, labelSize.height);//计算UILabel的rect          [tmpLabel setFrame:labelRect];          [tmpButton setFrame:CGRectMake(0, labelSize.height+1, 100, 50)];//计算UIButton 子控件的rect          [cell setFrame:CGRectMake(0, 0, labelSize.width, labelSize.height+50+1)];//cell的frame是以上两个子控件之和          return cell;  } 
为何不再创建时设置frame,而是在if和else逻辑后面? 重用cell的时候,从重用cell队列里面取出的cell,其内容(UILabel)是之前的cell内容,需要重新填充UILabel并且重新计算 整个cell的frame并设置其frame。而创建cell的时候也需要设置frame,所以这两个逻辑重复,直接放在if else逻辑外面做。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部