相仿九宫格的tableViewCell

类似九宫格的tableViewCell

  晚年也过了,新的一年真正来临了,迎着太阳向着远方,来冒个泡

  之前看到有花香太奇的九宫格,纯button实现的,感觉table更好用,就写了tableviewcell的,不是很难,主要还是view多了,怎么区分的问题,先上代码吧

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	int row=indexPath.row;
	
	NSString *indentifier=@"cell";
	
	UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
	
	if(cell==nil){
		cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
		
		int width=(1024-320-itemNumPerRow*10)/itemNumPerRow;

		for(int i=0;i<itemNumPerRow;i++){
			MediaView *itemView=[[MediaView alloc] initWithFrame:CGRectMake(i*width+10, 0, width, RowHeight)];
			itemView.backgroundColor=[UIColor clearColor];
			itemView.delegate=self;
			[itemView setTag:i+1];
			itemView.mediaTag=row*itemNumPerRow+i+1;
			
			itemView.mediaImage=[UIImage imageNamed:@"aaa.png"];
			
			[cell.contentView addSubview:itemView];
		}
	}
	else{
		for(int i=0;i<itemNumPerRow;i++){
			MediaView *itemView=(MediaView *)[cell.contentView viewWithTag:i+1];
			itemView.mediaTag=row*itemNumPerRow+i+1;
			
			itemView.mediaImage=[UIImage imageNamed:@"aaa.png"];
		}
	}
	
	cell.selectionStyle=UITableViewCellSelectionStyleNone;
	
	return cell;
}

 

  MediaView是自定义的view,重写了一下draw函数,复杂的话还可以加入响应的按钮和delegate之类的

#import <UIKit/UIKit.h>

#define MarginLeft 10
#define MarginRight 10
#define MarginTop 10
#define MarginBottom 35

@interface MediaView : UIView {
	UIImage *mediaImage;
	
	int mediaTag;
}

@property int mediaTag;

#import "MediaView.h"

@implementation MediaView

- (void)drawRect:(CGRect)rect {
    // Drawing code.
	int imageWidth=self.frame.size.width-MarginLeft-MarginRight;
	int imageHeight=self.frame.size.height-MarginTop-MarginBottom;
	CGRect imageRect=CGRectMake(MarginLeft, MarginTop, imageWidth, imageHeight);
	[self.mediaImage drawInRect:imageRect];
	 
	CGRect textRect=CGRectMake(MarginLeft, self.frame.size.height-MarginBottom, imageWidth, MarginBottom);
	[[UIColor blueColor] set];
	[@"test" drawInRect:textRect withFont:[UIFont systemFontOfSize:15]];
}

 

  我一直习惯用if--else来填充cell,if里面初始化各种view的UI,并且设置相对固定的tag,else里面根据tag找到重用的控件,动态填充数据,动态的部分是用mediaTag来实现的

 

PS:有人问过有木有demo,从项目中抽了出来

1 楼 gekie 2011-07-26  
有贴图更好。