九宫格

来源:互联网 发布:javascript常用框架 编辑:程序博客网 时间:2024/05/15 19:01

  // 书的九宫格位置

//  双重for循环实现    

#define BTN_WIDTH 136


#define BTN_HEIGHT 192


    int row = 200;

int col = 242;

    

    for (int i = 0 ; i < 5; i++) {

        

        for (int j =0; j <3; j++) {

            

            int x =  47 + i * row;

            

            int y = 64 + j * col;


            UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

            

            

            button.frame  = CGRectMake(x, y, BTN_WIDTH, BTN_HEIGHT);

            

            

            

            [button addTarget:selfaction:@selector(openDetailViewController)forControlEvents:UIControlEventTouchUpInside];

            

            

//            button.backgroundColor = [UIColor redColor];

            

            [cell addSubview:button];


        }

        

    }


// 单重for 循环 有可能不是刚好的九个


int  _menuCount = 11;

    

    int row;

    

    //计算栏目一共需要显示的行数

    if (_menuCount % 3 >0) {

        //有余数,说明有一行栏目数不足3,但是又需要多加一行

        row = _menuCount / 3 + 1;

    }

    else

    {

        //余数为0,正好是整数行

        row = _menuCount / 3;

    }

    int menuWidth = 80;

    int menuHeight = 80;

    //列间隙

    int verticalSpace = (320  -3 *menuWidth) / 4;

    int horizontalSpace = 40;

    

    //计算每个栏目的位置

    //i 表示行号

    for (int  i = 0 ; i < row ; i++) {

        //j表示列序号

        for (int j =0 ; j <3; j++) {

            if(i * 3 + j  < _menuCount)//防止创建多余的按钮

            {

                

                UIButton *menuBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];

               

                menuBtn.backgroundColor = [UIColorredColor];

                

                menuBtn.tag = i * 3 + j + 1;

                [menuBtn addTarget:selfaction:@selector(showMovieList:)forControlEvents:UIControlEventTouchUpInside];

                int x = (j + 1) * verticalSpace + j *menuWidth;

                int y = (i + 1) * horizontalSpace + i * menuHeight;

                menuBtn.frame = CGRectMake(x, y, menuWidth, menuHeight);

                [self.viewaddSubview:menuBtn];

                

            }

        }

    }



0 0