九宫格布局方法抽取

  • 测试效果


    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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容