例子1
{
// 一行最多4列
int maxCols = 4;
// 寬度和高度
CGFloat buttonW = XMGScreenW / maxCols;
CGFloat buttonH = buttonW;
for (int i = 0; i<sqaures.count; i++) {
// 創(chuàng)建按鈕
XMGSqaureButton *button = [XMGSqaureButton buttonWithType:UIButtonTypeCustom];
// 監(jiān)聽點擊
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
// 傳遞模型
button.square = sqaures[i];
[self addSubview:button];
// 計算frame
int col = i % maxCols;
int row = i / maxCols;
button.x = col * buttonW;
button.y = row * buttonH;
button.width = buttonW;
button.height = buttonH;
// 2.或者這個方法
// self.height = CGRectGetMaxY(button.frame);
}
// 總行數(shù)
// NSUInteger rows = sqaures.count / maxCols;
// if (sqaures.count % maxCols) { // 不能整除, + 1
// rows++;
// }
// 總頁數(shù) == (總個數(shù) + 每頁的最大數(shù) - 1) / 每頁最大數(shù)
NSUInteger rows = (sqaures.count + maxCols - 1) / maxCols;
// 計算footer的高度
self.height = rows * buttonH;
// 重繪
[self setNeedsDisplay];
}
例子2
{
// 每一個商品的尺寸
CGFloat shopW = 80;
CGFloat shopH = 90;
// 一行的列數(shù)
int cols = 3;
// 每一列之間的間距
CGFloat colMargin = (self.shopsView.frame.size.width - cols * shopW) / (cols - 1);
// 每一行之間的間距
CGFloat rowMargin = 10;
// 創(chuàng)建一個父控件(整體:存放圖片和文字)
XMGShopView *shopView = [XMGShopView shopView];
// 商品的索引
NSUInteger index = self.shopsView.subviews.count;
// 給商品控件傳遞商品模型
shopView.shop = self.shops[index];
// 商品的x值
NSUInteger col = index % cols;
CGFloat shopX = col * (shopW + colMargin);
// 商品的y值
NSUInteger row = index / cols;
CGFloat shopY = row * (shopH + rowMargin);
shopView.frame = CGRectMake(shopX, shopY, shopW, shopH);
// 添加控件
[self.shopsView addSubview:shopView];
// 控制按鈕的可用性
[self checkState];
}
3.萬能公式 計算九宮格高度
// 一行最多4列
int maxCols = 4;
// 總頁數(shù) == (總個數(shù) + 每頁的最大數(shù) - 1) / 每頁最大數(shù)
NSUInteger rows = (sqaures.count + maxCols - 1) / maxCols;
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者