九宮格布局方法抽取

  • 測試效果


    Sudoku.png
  • 使用時只需要一行代碼

[Sudoku sudokuWithColumn:5 line:4 objectWidth:65 height:75 inTheSuperView:_testView];
  • 單獨寫了個類
#import "Sudoku.h"

@implementation Sudoku

/**
 * 核心思路:
 * 列的x值一樣,行的y值一樣
 * x值=列號 *(子控件寬+列間距),y值=行號 *(子控件高+行間距)
 * 列號=index%列數,行號=index/列數    ----計算時依靠固定列數
 */
+ (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);
    
    // 父控件中已經添加的子控件個數
    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);
    
    // 創建要添加的控件
    UIView *objectView = [[UIView alloc] init];
    objectView.backgroundColor = [UIColor yellowColor];
    objectView.frame = CGRectMake(objectX, objectY, objectW, objectH);
    [theSuperView addSubview:objectView];
    
    theSuperView.clipsToBounds = YES;
}
@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容