九宫格-选中变色-单选项

来源:互联网 发布:公安民警网络答题 编辑:程序博客网 时间:2024/06/11 01:07
////  ViewController.m//  SelectedButtonDemo////  Created by 逍遥子 on 16/1/22.//  Copyright © 2016年 QuantGroup. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (strong,nonatomic)UIButton*starButton;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        [self creatNineBox];}-(void)creatNineBox{    //设置九宫格按钮显示的title数组    NSArray *titileArray = @[@"无知",@"风云变幻",@"施耐庵"];    //      总列数    int totalColumns = 3;        //       每一格的尺寸    CGFloat cellW = 100;    CGFloat cellH = 40;        //    间隙    CGFloat margin =(self.view.frame.size.width - totalColumns * cellW) / (totalColumns + 1);        //    根据格子个数创建对应的框框    for(int index = 0; index< titileArray.count; index++) {        UIButton *boxBtn = [UIButton buttonWithType:UIButtonTypeCustom];        //设置tag        boxBtn.tag=index+666;        boxBtn.backgroundColor = [UIColor whiteColor];        boxBtn.layer.borderColor=[UIColor grayColor].CGColor;        boxBtn.layer.borderWidth=1;        boxBtn.layer.cornerRadius=3;        [boxBtn setTitle:[titileArray objectAtIndex:index] forState:UIControlStateNormal];        [boxBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];        boxBtn.titleLabel.font=[UIFont systemFontOfSize:12];        // 计算行号  和   列号        int row = index / totalColumns;        int col = index % totalColumns;        //根据行号和列号来确定 子控件的坐标        CGFloat cellX = margin + col * (cellW + margin);        CGFloat cellY = row * (cellH + margin);//        下移100        boxBtn.frame = CGRectMake(cellX, cellY +200, cellW, cellH);                [boxBtn addTarget:self action:@selector(selectedBtnPress:) forControlEvents:UIControlEventTouchUpInside];        // 添加到view 中          [self.view addSubview:boxBtn];    }}- (void)selectedBtnPress:(UIButton*)sender{    //遍历一下、找到我们的按钮    for (id obj in self.view.subviews)  {        if ([obj isKindOfClass:[UIButton class]]) {            UIButton* theButton = (UIButton*)obj;            //为我们选中和不被选中的按钮设置不同的颜色            if (theButton.tag ==sender.tag) {                theButton.backgroundColor =[UIColor orangeColor];                theButton.layer.borderColor=[UIColor orangeColor].CGColor;                [theButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];            }else{                theButton.backgroundColor =[UIColor whiteColor];                theButton.layer.borderColor=[UIColor grayColor].CGColor;                [theButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];            }        }    }}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

效果


0 0