针对类似 UICollectionView当横向滚动时,显示顺序保持竖向滚动时的排序转换方法
OC
- (void)viewDidLoad {
[super viewDidLoad];
// 示例数组
NSMutableArray *array = [@[] mutableCopy];
for (int i = 0; i < 23; i++) {
[array addObject:@(i)];
}
NSArray *list = [self convertSortRowToColumnWithArray:array columns:5 rows:3];
for (NSNumber *num in list) {
NSLog(@">>%ld", [num integerValue]);
}
}
- (NSArray *)convertSortRowToColumnWithArray:(NSArray *)list columns:(NSInteger)column rows:(NSInteger)row {
if (column < 2 || row < 2 || list.count < 3) {
return list;
}
// 分页
NSInteger count = list.count;
NSInteger pages = count / (column * row);
NSInteger remainder = count % (column * row);
if (remainder) {
pages += 1;
}
NSMutableArray *result = [@[] mutableCopy];
NSInteger length = column * row;
for (int i = 0; i < pages; i++) {
NSInteger location = i * length;
if (i == pages - 1) {
length = count - location;
}
NSArray *segment = [list subarrayWithRange:NSMakeRange(location, length)];
// 重排序
segment = [self sortByColumnWithArray:segment columns:column rows:row];
[result addObjectsFromArray:segment];
}
return [result copy];
}
- (NSArray *)sortByColumnWithArray:(NSArray *)list columns:(NSInteger)column rows:(NSInteger)row {
NSInteger count = list.count;
NSMutableArray *array = [@[] mutableCopy];
// 先计算能排多少列
NSInteger realColumn = count / row;
NSInteger remainder = count % row;
if (remainder) {
realColumn += 1;
}
for (int i = 0; i < realColumn; i++) {
NSMutableArray *columnArray = [NSMutableArray arrayWithCapacity:row];
for (int j = 0; j < row; j++) {
NSInteger index = i + j * realColumn;
if (index < count) {
[columnArray addObject:list[index]];
}
}
[array addObjectsFromArray:columnArray];
}
return [array copy];
}
Swift
// 当 UICollectionView 横向分页时,item默认排序是竖向排序,此方法转化为横向排序
static func convertSortRowToColumn(list: [Any], columns column:Int, rows row:Int) -> [Any] {
if (column < 2 || row < 2 || list.count < 3) { return list }
// 分页
let count = list.count;
var pages = count / (column * row)
let remainder = count % (column * row)
if (remainder > 0) { pages += 1 }
var result: [Any] = []
var length = column * row
for i in 0..<pages {
let location = i * length
if (i == pages - 1) { length = count - location }
var segment: [Any] = []
for index in 0..<count {
if index >= location && index < (location + length) {
segment.append(list[index])
}
}
// 重排序
segment = LENTools.sortByColumn(list: segment, columns: column, rows: row)
result += segment
}
return result
}
private static func sortByColumn(list: [Any], columns column:Int, rows row:Int) -> [Any] {
let count = list.count
var array: [Any] = []
// 先计算能排多少列
var realColumn = count / row
let remainder = count % row
if (remainder > 0) { realColumn += 1 }
for i in 0..<realColumn {
var columnArray: [Any] = []
for j in 0..<row {
let index = i + j * realColumn;
if (index < count) { columnArray.append(list[index]) }
}
array += columnArray
}
return array
}
网友评论