TableView中画Cell的三种方法

UITableViewCell自定义与重用
本文介绍了一种UITableViewCell自定义的方法,并通过实例演示了如何利用字典存储自定义的UIView来实现UITableViewCell的重用机制。文章详细展示了创建自定义cell的过程,包括布局设置、字体颜色配置等。
一、直接在 if(cell == nil){} 中写,不在阐述
 
二、引入自定义cell,参见橘子皮那本iphone P159页 UITableViewCell自定义子类
 
三、其中的chatDictionary 、chatArray 分别为全局的字典、可变数组
每个cell都对应一个字典:chatDictionary (放在可变数组chatArray 中),在字典中通过key"view"获得其对应的值(既名字为cell的UIView),在cellForRow方法中add到cell的子试图即可,代码如下:
 
- (void)viewDidLoad
{
    [self makeTableViewCell];(写在其他方法中也可以,只要在table 加载之前调用就行)
}
 
- (void) makeTableViewCell
{
 [chatArray removeAllObjects];
 
 for (int i = 0; i < [parser.newsList count]; i++)
 {
  DnsNews *news = [parser.newsList objectAtIndex:i];
  
  UIView *cell = [[UIView alloc] initWithFrame:CGRectZero];
  cell.backgroundColor = [UIColor clearColor];
  
  // 标题字体
  UIFont *titleFont = [UIFont systemFontOfSize:18];
  // 标题
  UILabel *titleText = [[UILabel alloc] initWithFrame:CGRectMake(90.0f, 2.0f, 215.0f, 20.0f)];
  titleText.backgroundColor = [UIColor clearColor];
  titleText.font = titleFont;
  titleText.textColor = [UIColor colorWithRed:50/255.f green:152/255.f blue:195/255.f alpha:1.0];
  titleText.numberOfLines = 1;
  titleText.lineBreakMode = UILineBreakModeCharacterWrap;
  titleText.text = news.title;
  
  [cell addSubview:titleText];
  [titleText release];

  cell.frame = CGRectMake(0.0f, 0.0f, 320.0f, 22.0f + 40.0f);
  
  [chatDictionary setObject:cell forKey:@"view"];
  [chatArray addObject:[NSDictionary dictionaryWithDictionary:chatDictionary]];
 }
 
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 UITableViewCell *cell;
 NSUInteger row = [indexPath row];

  static NSString *NewsCellTableIdentifier = @"NewsCellTableIdentifier";
  cell = [aTableView dequeueReusableCellWithIdentifier:NewsCellTableIdentifier];
  if (!cell)
  {
   cell = [[[UITableViewCell alloc]
      initWithStyle:UITableViewCellStyleDefault
      reuseIdentifier:NewsCellTableIdentifier] autorelease];
  }
  
  // 移除cell中已经存在的控件,避免出现数据重叠现象
  for(UIView *subview in [cell.contentView subviews])
  {
   [subview removeFromSuperview];
  }
  NSDictionary *_chatDictionary = [chatArray objectAtIndex:row];
  [cell.contentView addSubview:[_chatDictionary objectForKey:@"view"]];
  
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 
  return cell;
}
个人认为这个方法没有很好的使用Cell的重用机制
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值