iOS - for迴圈快捷建立按鈕(隨意配置適配)
阿新 • • 發佈:2020-12-10
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; }