UITableView示例二——九宫格.
一、代码
1.XmCell.h
#import <UIKit/UIKit.h>
#define kStartTag 1000
#define kCountPerButton 4
#define kTotalButton 50
@interface XmCell : UITableViewCell
@end
2.XmCell.m
#import "XmCell.h"
@implementation XmCell
#pragma 构造方法
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
for (NSInteger i=0; i<kCountPerButton; i++) {
NSInteger butonWidth = 375.0/kCountPerButton;
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(i*butonWidth, 0, butonWidth, 100)];
[button setTag:i+kStartTag ];
[self.contentView addSubview:button];
}
}
return self;
}
- (void)awakeFromNib {
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
@end
3.ViewController.m
#import "ViewController.h"
#import "XmCell.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITableView * tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
[tableView setDataSource:self];
[tableView setDelegate:self];
[self.view addSubview:tableView];
[tableView registerClass:[XmCell class] forCellReuseIdentifier:@"XmCell"];
}
#pragma mark - 行数
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(@"行数:%d",(kTotalButton-1)/kCountPerButton +1);
return (kTotalButton-1)/kCountPerButton +1;
}
#pragma mark - 单元格
-(UITableViewCell*)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
static NSString * identifier = @"XmCell";
XmCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
for (NSInteger i=0; i<kCountPerButton; i++) {
NSString * path = [NSString stringWithFormat:@"tmall_icon_cat_outing_%d.png",arc4random_uniform(12)+1];
UIImage * image = [UIImage imageNamed:path];
UIButton * button = (UIButton*)[cell.contentView viewWithTag:i+kStartTag];
[button setImage:image forState:UIControlStateNormal];
if (kCountPerButton * indexPath.row + i < kTotalButton ) {
[button setHidden:NO];
}else{
[button setHidden:YES];
}
}
return cell;
}
#pragma mark - 行高
-(CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
return 100;
}
@end
二、图示