你的位置:首页 > 操作系统

[操作系统]IOS中实现九宫格


实现九宫格的算法思路:

 

具体示例:

 1 // 2 // ViewController.m 3 // 九宫格 4 // 5 // Created by 李前途 on 15/3/26. 6 // Copyright (c) 2015年 李前途. All rights reserved. 7 // 8  9 #import "ViewController.h"10 11 @interface ViewController ()12 13 @property (nonatomic,strong) NSArray *data;14 @end15 16 @implementation ViewController17 18 - (NSArray *)data{19   if (_data == nil) {20     NSString *fileName= [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];21     _data = [NSArray arrayWithContentsOfFile:fileName];22   }23   24   return _data;25 }26 27 - (void)viewDidLoad {28   [super viewDidLoad];29   30   int colNumber = 3;31   32   CGFloat appW = 85;33   CGFloat appH = 90;34   35   36   CGFloat marginX = (self.view.frame.size.width - appW * colNumber) / (colNumber + 1);37   CGFloat marginY = 15;38   39   for (int index = 0; index < self.data.count; index++) {40     int row = index / colNumber;41     int col = index % colNumber;42     CGFloat appX = col * (appW + marginX) + marginX;43     CGFloat appY = row * (appH + marginY) + 30;44     UIView *appView = [[UIView alloc] init];45 //    appView.backgroundColor = [UIColor greenColor];46     appView.frame = CGRectMake(appX, appY, appW, appH);47     [self.view addSubview:appView];48     49     NSDictionary *dataDic = self.data[index];50     UIImageView *iconImg = [[UIImageView alloc] init];51     CGFloat iconW = 45;52     CGFloat iconH = 45;53     CGFloat iconX= (appW - iconW) / 2;54     CGFloat iconY = 0;55     iconImg.frame = CGRectMake(iconX, iconY, iconW, iconH);56     iconImg.image = [UIImage imageNamed:dataDic[@"icon"]];57     [appView addSubview:iconImg];58    59     60     UILabel *label = [[UILabel alloc] init];61     CGFloat labelW = appW;62     CGFloat labelH = 25;63     CGFloat labelX = 0;64     CGFloat labelY = iconH;65     label.frame = CGRectMake(labelX, labelY, labelW, labelH);66     label.text = dataDic[@"name"];67     label.font = [UIFont systemFontOfSize:13];68     label.textAlignment = NSTextAlignmentCenter;69     [appView addSubview:label];70     71     UIButton *btn = [[UIButton alloc] init];72     CGFloat btnX = 12;73     CGFloat btnY = labelY + labelH;74     CGFloat btnW = appW - 2 * btnX;75     CGFloat btnH = 20;76     btn.frame = CGRectMake(btnX, btnY, btnW, btnH);77     [btn setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];78     [btn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];79     [btn setTitle:@"下载" forState:UIControlStateNormal];80     btn.titleLabel.font = [UIFont systemFontOfSize:11];81     [appView addSubview:btn];82     83   }84   85   86   87 }88 89 - (void)didReceiveMemoryWarning {90   [super didReceiveMemoryWarning];91   // Dispose of any resources that can be recreated.92 }93 94 @end