UICollectionView高度計算
思路:collectionView高度需要根據內容去計算=>有數據了再計算高度。(collectionView不需要滾動)
①高度計算
拿到數據源之后計算:
static NSString * const ID = @"cell"; static NSInteger const cols = 4; static CGFloat const margin = 1; #define itemWH (SCREEN_WIDTH - (cols - 1) * margin) / cols // 處理數據 [self resloveData]; //計算collectionView高度 = rows * itemWH //Rows = (count - 1) / cols + 1 NSInteger count = self.squareItems.count; NSInteger rows = (count - 1) / cols + 1; // 設置collectioView高度 self.collectionView.height = rows * itemWH; self.tableView.tableFooterView = self.collectionView; // 設置tableView滾動范圍:自己計算 //self.tableView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.collectionView.frame)); // 刷新表格 [self.collectionView reloadData];
②數據處理(判斷缺幾個)
#pragma mark - 處理請求完成數據 - (void)resloveData { // 判斷下缺幾個 // 3 % 4 = 3 cols - 3 = 1 // 5 % 4 = 1 cols - 1 = 3 NSInteger count = self.squareItems.count; NSInteger exter = count % cols; if (exter) { exter = cols - exter; for (int i = 0; i < exter; i++) { HKSquareItem *item = [[HKSquareItem alloc] init]; [self.squareItems addObject:item]; } } if ([self.squareItems containsObject:@[]]) { [self.squareItems removeObject:@[]]; } }
效果圖:
