学习九宫格的实现,一个for循环


//

//  ViewController.m

//  tony

//

//  Created by Tony on 15/9/25.

//  Copyright (c) 2015 Tony. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()

@property(nonatomic,strong)NSMutableArray *apps;

@end


@implementation ViewController


- (NSMutableArray *)apps

{

   if (_apps==nil) {

        _apps=[NSMutableArrayarray];

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

           NSDictionary *dict=@{@"title":[NSStringstringWithFormat:@"超级复读机%d",i]};

            [_appsaddObject:dict];

            

        }

    }

   return_apps;

}

- (void)viewDidLoad {

    [superviewDidLoad];


   int columns=3;//每行的个数

    CGFloat viewWidth=self.view.frame.size.width;

    

   CGFloat appW=75;//子控件宽度

   CGFloat appH=90;//子控件高度

   CGFloat marginTop=30;//第一行距离

   CGFloat marginX=(viewWidth-columns*appW)/(columns+1);//横向marginX的间距值

   CGFloat marginY=marginX;//Y间距的值跟X一样

    

   for (int i=0; i<self.apps.count; i++) { //由数组来决定个控件要实现九宫格


       NSDictionary *dict=self.apps[i];

       int xId=i%columns;//得到列索引

       CGFloat appX=marginX+xId*(appW+marginX); //取每个控件的X位置

        

       int yId=i/columns;//得到行索引

       CGFloat appY=marginTop+yId*(appH+marginY);//取每个控件的Y位置

        

       UIView *appView=[[UIViewalloc]init];

        appView.frame=CGRectMake(appX, appY, appW, appH);//设置坐标

        appView.backgroundColor=[UIColorgrayColor];

        [self.viewaddSubview:appView];

        

        //uiview增加子控件

       UIImageView *imageIcon=[[UIImageViewalloc]init];

        imageIcon.backgroundColor=[UIColoryellowColor];

       CGFloat iconW=45;

       CGFloat iconH=45;

       CGFloat iconX=(appView.frame.size.width-iconW)*0.5;

       CGFloat iconY=0;

        imageIcon.frame=CGRectMake(iconX, iconY, iconW, iconH);

        [appViewaddSubview:imageIcon];

        

       UILabel *lblbName=[[UILabelalloc]init];

        lblbName.backgroundColor=[UIColorwhiteColor];

        lblbName.text=dict[@"title"];

       NSLog(@"%@",dict[@"title"]);

        lblbName.font=[UIFontsystemFontOfSize:12];

        lblbName.frame=CGRectMake(0, iconH, appW,20);

        [appViewaddSubview:lblbName];

        

       UIButton *btnDownload=[[UIButtonalloc]initWithFrame:CGRectMake(iconX,lblbName.frame.origin.y+lblbName.frame.size.height+5, iconW, 20)];

        btnDownload.backgroundColor=[UIColorpurpleColor];

        [appViewaddSubview:btnDownload];

        

        [btnDownload setTitle:@"下载"forState:UIControlStateNormal];

        [btnDownload setTitle:@"已下载"forState:UIControlStateDisabled];

        

    }

    

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值