循环创建按钮
CGFloat margin = 22; CGFloat btnW = 35; CGFloat btnH = 35; int cloums = 7; CGFloat btnLeft = (self.view.frame.size.width - (btnW * cloums) - (cloums - 1) * margin) / 2; for (int i = 0; i < 30; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; // 行的索引 int colIdx = i % cloums; // 列的索引 int rowIdx = i / cloums; CGFloat btnX = btnLeft + colIdx * (btnW + margin); CGFloat btnY = 0 + rowIdx * (btnH + margin); button.frame = CGRectMake(btnX, btnY, btnW, btnH); button.backgroundColor = [UIColor redColor]; [self.view addSubview:button]; } 来源: https://www.cnblogs.com/fantasy3588/p