iOS-for循环快捷创建按钮(随意配置适配)

One

先总结下最近做项目遇到的一个小问题,创建UIView时,总是有一边会出现一条灰黑线,原因竟是在给view设置frame时的精确度问题,取整下即可;

ceilf(width)

Two

最近在项目里帮朋友简单写了一下这个需求,记录下以后用到方便配置,项目中的我可以放心删了;

#define demoScale  CGRectGetWidth([[UIScreen mainScreen] bounds])/375.0
- (void)forDemo{
    UIView *contentView = self.view;
    ///按钮总个数
    NSInteger allCount = 16;
    ///按钮每行总个数
    NSInteger elCount = 5;
    ///左右边距
    CGFloat marginLR = 25*demoScale;
    ///上下边距
    CGFloat marginTD = 10*demoScale;
    ///button左右之间的间隔(item间距)
    CGFloat lineSpace = 30*demoScale;
    ///button上下之间的间隔(行间距)
    CGFloat columnSpace = 20*demoScale;
    ///button宽
    CGFloat btnWidth = (CGRectGetWidth(contentView.bounds) - marginLR*2 - lineSpace*(elCount-1))/elCount;
    ///button高
    CGFloat btnHeight = 50*demoScale;

    for (int i = 0; i < allCount; i ++) {
        CGFloat btnX = marginLR + (i%elCount)*(btnWidth + lineSpace);
        CGFloat btnY = marginTD + (i/elCount)*(btnHeight + columnSpace);
        NSLog(@"%f,%f",btnX,btnY);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor redColor];
        button.frame = CGRectMake(btnX , btnY, btnWidth, btnHeight);
        [contentView addSubview:button];
    }

    NSInteger columnNumber = (allCount/elCount);
    CGFloat contentViewHeiht = marginTD*2 + columnSpace*(columnNumber-1) +  columnNumber*btnHeight;
}
原文地址:https://www.cnblogs.com/wangkejia/p/14116297.html