九宫格计算思路
九宫格思路
/******** 九宫格计算思路 ******* 00 01 02————0行 10 11 12————1行 处在同一行的y一样 20 21 22————2行 处在同一列的x一样 | | | | | | 0 1 2 列 列 列 ****************************/
程序示例
// // ViewController.m // My09-综合使用 // // Created by 陈德豪 on 16/5/11. // Copyright © 2016年 chendehao. All rights reserved. // #import "ViewController.h" @interface ViewController () //@property (weak, nonatomic) IBOutlet UIScrollView *shopBag; @property (weak, nonatomic) IBOutlet UIView *shopPocket; @property (weak, nonatomic) IBOutlet UIButton *addButton; @property (weak, nonatomic) IBOutlet UIButton *removeButton; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } #pragma mark - 添加 - (IBAction)add { /****** 定义数据变量 *******/ // 定义商品总的列数 NSUInteger maxRanks = 3; // 定商品的宽度 CGFloat shopW = 70; // 定商品的高度 CGFloat shopH = 90; // 获取商品父控件的索引 NSUInteger index = self.shopPocket.subviews.count; /***************** 计算 X 和 Y ********************/ // 计算所在列号 NSUInteger rank = index % maxRanks ; // 计算所在行号 NSUInteger row = index / maxRanks ; // 计算商品x轴上之间的间距 CGFloat xSpace = ( self.shopPocket.frame.size.width - shopW * maxRanks ) / ( maxRanks - 1 ); // 定义商品Y轴上之间的距离 CGFloat ySpace = 20 ; /***************** 计算 商品的位置信息 ********************/ CGFloat shopX = (shopW + xSpace) * rank; CGFloat shopY = (shopH + ySpace) * row; // 1. 创建一个UIView 容器,放置商品image控件和商品label控件,这里称之为商品父控件 UIView *shopView = [[UIView alloc]init]; // 定义shopView 的尺寸大小 shopView.frame = CGRectMake(shopX, shopY, shopW, shopH); // 将商品父控件 添加入控制器 购物袋 [self.shopPocket addSubview:shopView]; // 2. 创建一个商品imageView控件,存放商品图片 UIImageView *shopImageView = [[UIImageView alloc]init ]; // 定义shopImageView的位置和尺寸 shopImageView.frame = CGRectMake(0, 0, shopW, shopW); // 获取图片 shopImageView.image = [UIImage imageNamed:@"qianbao"]; // 将图片窗口添加到商品父控件shopView 中 [shopView addSubview:shopImageView]; // 3. 创建一个商品名称的label,存放商品名称 UILabel * nameLabel = [[UILabel alloc]init ]; // 设置对其方式 nameLabel.textAlignment = NSTextAlignmentCenter; // 定义 namelabel de 位置和尺寸 nameLabel.frame = CGRectMake(0, shopW, shopW, shopH - shopW ); // 设置label 中文本内容 nameLabel.text = @"钱包"; // 将nameLabel放入商品父控件shopView中; [shopView addSubview:nameLabel]; /**************** 控制按钮的状态 ***************/ self.removeButton.enabled = YES; self.addButton.enabled = (self.shopPocket.subviews.count < 6); } #pragma mark - 删除 - (IBAction)remove { // 移除最后一个商品的父控件 [self.shopPocket.subviews.lastObject removeFromSuperview]; /**************** 控制按钮的状态 ***************/ self.addButton.enabled = YES; self.removeButton.enabled = (self.shopPocket.subviews.count > 0); } @end