要在表格视图中创建简单的网格视图,请创建类“GridViewCell”并在头文件中添加:
@interface GridViewCell : UITableViewCell
@property (nonatomic, strong) UIButton *column1;
@property (nonatomic, strong) UIButton *column2;
@property (nonatomic, strong) UIButton *column3;
@end
在 .m 文件中添加以下代码:
#define CELL_WIDTH 100
#define CELL_HEIGHT 80
#import "GridViewCell.h"
@implementation GridViewCell
@synthesize column1, column2, column3;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
column1 = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, CELL_WIDTH, CELL_HEIGHT)];
[self addSubview:column1];
column2 = [[UIButton alloc] initWithFrame:CGRectMake(CELL_WIDTH+ 10, 5, CELL_WIDTH, CELL_HEIGHT)];
[self addSubview:column2];
column3 = [[UIButton alloc] initWithFrame:CGRectMake(CELL_WIDTH + CELL_WIDTH + 15, 5, CELL_WIDTH, CELL_HEIGHT)];
[self addSubview:column3];
}
return self;
}
@end
当您创建表时,在委托 cellForRowAtIndexPath 中使用新类“GridView”:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
GridViewCell *cell = (GridViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[GridViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[cell.column1 setBackgroundColor:[UIColor blackColor]];
[cell.column2 setBackgroundColor:[UIColor blackColor]];
[cell.column3 setBackgroundColor:[UIColor blackColor]];
return cell;
}