我们经常看到很多UI界面都有涉及到多宫格表格,对于这类界面,我们一般用UICollectionView来实现它。但是,对于一些特殊的界面,用UICollectionView会显得比较麻烦。我们可以自定义一个View视图来显示它。
一、创建ListView,继承于UIView。在.h里添加选中回调方法
@interface ListView : UIView
/**
选中回调 type值表示对应的显示视图
*/
@property (nonatomic, copy) void (^detailTapMethond)(NSInteger type);
/**
根据实际需求,声明对应对象
*/
/**
详情数据
*/
@property (nonatomic, strong) NSArray *detail_arr;
/**
详情图标数据
*/
@property (nonatomic, strong) NSArray *detailImg_arr;
@end
.m里实现
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor groupTableViewBackgroundColor];
[self addSubDetailViews];
}
return self;
}
/**
详情数据
*/
- (NSArray *)detail_arr{
if (_detail_arr == nil) {
_detail_arr = @[@"swift",@"swift",@"swift",@"swift",@"swift",@"swift",@"swift",@"swift"];
}
return _detail_arr;
}
/**
详情图标数据
*/
- (NSArray *)detailImg_arr{
if (_detailImg_arr == nil) {
_detailImg_arr = @[@"bullet_default",@"bullet_default",@"bullet_default",@"bullet_default",@"bullet_default",@"bullet_default",@"bullet_default",@"bullet_default"];
}
return _detailImg_arr;
}
/**
加载详情子控件
*/
- (void)addSubDetailViews{
int count = 15;//可以根据实际需求设置显示的View个数
for (int i = 0; i < count; i++) {
CGFloat width = (self.frame.size.width-2.0)/3.0;
CGFloat height =(self.frame.size.height-4.0)/5.0;
CGFloat x = (i%3)*(width+2.0/3.0);
CGFloat y = (i/3)*(height+4.0/5.0);
UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
baseView.backgroundColor = [UIColor whiteColor];
baseView.tag = 100+i;
[self addSubview:baseView];
if (i < self.detail_arr.count) {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(detailTapMethond:)];
[baseView addGestureRecognizer:tap];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(baseView.frame.size.width * (90.0/350.0), baseView.frame.size.height*(66.0/340.0), baseView.frame.size.width * (170.0/350.0), baseView.frame.size.height*(170.0/340.0))];
imageView.image = [UIImage imageNamed:self.detailImg_arr[i]];
[baseView addSubview:imageView];
UILabel *nameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, baseView.frame.size.height*(260.0/340.0), baseView.frame.size.width, baseView.frame.size.height*(54.0/340.0))];
nameLab.text = self.detail_arr[i];
nameLab.textColor = [UIColor darkTextColor];
nameLab.textAlignment = NSTextAlignmentCenter;
[baseView addSubview:nameLab];
}
}
}
- (void)detailTapMethond:(UITapGestureRecognizer *)tap{
NSInteger count = tap.view.tag-100;
if (count < self.detail_arr.count) {
NSLog(@"count ---- %ld",count);
if (self.detailTapMethond) {
self.detailTapMethond(count);
}
}
}
二、在需要用到的VC里直接调用即可
/**
创建主视图
*/
- (void)creatMainView{
self.detail_view = [[ListView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
self.detail_view.detailTapMethond = ^(NSInteger type) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"根据返回的type值进入对应的视图");
});
};
[self.view addSubview:self.detail_view];
}
三、效果图

网友评论