-
測試效果
Sudoku.png 使用時只需要一行代碼
[Sudoku sudokuWithColumn:5 line:4 objectWidth:65 height:75 inTheSuperView:_testView];
- 單獨寫了個類
#import "Sudoku.h"
@implementation Sudoku
/**
* 核心思路:
* 列的x值一樣,行的y值一樣
* x值=列號 *(子控件寬+列間距),y值=行號 *(子控件高+行間距)
* 列號=index%列數(shù),行號=index/列數(shù) ----計算時依靠固定列數(shù)
*/
+ (void)sudokuWithColumn:(NSUInteger)column line:(NSUInteger)line objectWidth:(CGFloat)width height:(CGFloat)height inTheSuperView:(UIView *)theSuperView{
// 預定義
CGFloat objectW = width;
CGFloat objectH = height;
NSUInteger cols = column;
NSUInteger lines = line;
// margin計算
CGFloat colMargin = (theSuperView.frame.size.width - cols * objectW)/(cols - 1);
CGFloat rowMargin = (theSuperView.frame.size.height - lines * objectH)/(lines - 1);
// 父控件中已經(jīng)添加的子控件個數(shù)
NSUInteger index = theSuperView.subviews.count;
// x、y值計算(位置)
NSUInteger col = index % cols;
NSUInteger row = index / cols;
CGFloat objectX = col * (objectW + colMargin);
CGFloat objectY = row * (objectH + rowMargin);
// 創(chuàng)建要添加的控件
UIView *objectView = [[UIView alloc] init];
objectView.backgroundColor = [UIColor yellowColor];
objectView.frame = CGRectMake(objectX, objectY, objectW, objectH);
[theSuperView addSubview:objectView];
theSuperView.clipsToBounds = YES;
}
@end