ITEEDU

自定义tableViewCell类

上述自定义tableView代码中的注释已经很清楚了。 先设置视图的背景,再设定table view的背景,再看另外一段代码,设置了cell的背景,注意,这里面使用了自定义的cell类。

CustomCell 类:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	CustomCell *cell= [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];

	// Default to no selected style and not selected
	cell.selectionStyle = UITableViewCellSelectionStyleNone;

	// Set the image for the cell
	[cell setTheImage:[UIImage imageNamed:[NSString stringWithFormat:@"Arrows%d.png", indexPath.row + 1]]];

	return cell;
}

我们再看看如何定义自定义的cell :

声明类,CustomCell.h:

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell 
{
  UIImageView *image; 
}

- (void) setTheImage:(UIImage *)icon;

@end

再看实现类

#import "CustomCell.h"

@implementation CustomCell


-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
	if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) 
  {
    // Cells are transparent
    [self.contentView setBackgroundColor:[UIColor clearColor]];
	}

	return self;
}


- (void) setTheImage:(UIImage *) icon
{  
  // Alloc and set the frame
  image = [[UIImageView alloc] initWithImage:icon];
  image.frame = CGRectMake(0, 0, 286, 68);

  // Add subview
  [self.contentView addSubview:image];    
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{
  [super setSelected:selected animated:animated];   
  if (selected == YES)
    image.alpha = .5;
  else
    image.alpha = 1;
}


- (void)dealloc 
{
  [image release];
  [super dealloc];
}

@end

2.iPhone书架实现点击事件处理问题

利用tag来标记到底是点击了哪个按钮。

[btnOne setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:[listData objectAtIndex:(3*indexPath.row)],indexPath.row]] forState:UITouchPhaseEnded];
 btnOne.tag = 3*indexPath.row;
//采用在程序中计算出来,手工赋值实现。