iOS实现按钮九宫格
2018-09-20 本文已影响0人
染小七的代码
//
// ViewController.m
// 关于九宫格
//
#define btnMargin 20
#define col 6
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic , strong) UIView * bgView;
@property(nonatomic , strong) UIButton * classBtn;
@property(nonatomic, strong)NSMutableArray * classArr;
@end
@implementation ViewController
// 自定义数组
-(NSMutableArray *)classArr{
if (!_classArr) {
_classArr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8", @"9",@"10",@"11",@"12",nil];
}
return _classArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 0- 背景视图
self. bgView = [[UIView alloc]init];
self.bgView.frame =CGRectMake(0, 200, 475, 200);
self.bgView.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.bgView];
//开始计算
// 按钮宽
CGFloat btnwW = ([UIScreen mainScreen].bounds.size.width -(col+1)*btnMargin)/col;
CGFloat btnwH = 50;
for (int i = 0; i < self.classArr.count; i++) {
int a = i / col;
int b = i % col;
// 1- 自定义按钮
self.classBtn = [UIButton buttonWithType:UIButtonTypeCustom];
self.classBtn.frame =CGRectMake(b*btnwW+(btnMargin*(b+1)),a*btnwH+(btnMargin*(a+1)), btnwW, btnwH);
// 自定义按钮颜色来区分
if(i % 2 == 0){
self.classBtn.backgroundColor = [UIColor redColor];
}else{
self.classBtn.backgroundColor = [UIColor greenColor];
}
self.classBtn.tag = i;
[self.classBtn setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
self.classBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
[self.classBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.bgView addSubview:self.classBtn];
}
}
-(void) btnClick:(UIButton *) btn{
NSLog(@"----%ld",btn.tag);
}
@end
![1.jpg](https://img.haomeiwen.com/i2780168/e6781c7b701c9bcb.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)