五个UICollectionView经常使用的知识点

  • 一:监听滚动中止的时刻
  • 2、监听reloadData刷新列表完毕的时机
  • 3、自由拖拽
  • 4、瀑布流
  • 5、浮动的Header

一:监听滚动中止的时刻

场景一、手动拖拽屏幕中止

场景二、调用scrollToRow中止

场景三、调用setContentOffset中止

self.tableView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
print("执行这行代码的时候,已经滚动完毕")
复制代码

2、监听reloadData刷新列表完毕的时机

详情参考监听reloadData刷新列表完毕的时机git

  • 方法一、经过layoutIfNeeded方法,强制重绘并等待完成。
  • 方法二、reloadData方法会在主线程执行,经过GCD,使后续操做排队在reloadData后面执行。一次runloop有两个机会执行GCD dispatch main queue中的任务,分别在休眠前和被唤醒后。设置listViewlayoutIfNeeded为YES,在即将进入休眠时执行异步任务,重绘一次界面。
  • 方法三、自定义UICollectionViewUITableViewlayoutSubviews以后看成reloadData完成(复杂,但能够更好的理解方法一)

3、自由拖拽

1、iOS9以前思路:

  • 第一步 :给UICollectionviewCell添加一个长按手势UILongPressGestureRecognizer,经过代理传递到UIViewController中。
  • 第二步 :开始长按时(UIGestureRecognizerStateBegan)对cell进行截图而且隐藏cell
  • 第三步 :移动时(UIGestureRecognizerStateChanged)移动截图,遍历获得截图移动到哪一个cell的位置。调用方法moveItemAtIndexPath:toIndexPath:调换两个cell的位置,而且更新数据源的顺序。
  • 第四步 :中止时(UIGestureRecognizerStateEnded)移除截图,显示cell

参考博客:

[iOSUI 进阶拖] 拽排序的实现github

DraggingSortswift

LXReorderableCollectionViewFlowLayout数组

XWDragCellCollectionViewbash

CollectionViewCellDragExchange服务器

2、iOS9以后思路:

  • 第一步:给UICollectionviewCell添加一个长按手势UILongPressGestureRecognizer,经过代理传递到UIViewController中。
  • 第二步:开始长按时(UIGestureRecognizerStateBegan)对cell进行截图而且隐藏cell。调用beginInteractiveMovementForItem
  • 第三步:移动时(UIGestureRecognizerStateChanged)移动截图。调用updateInteractiveMovementTargetPosition
  • 第四步:中止时(UIGestureRecognizerStateEnded)移除截图,显示cell。调用endInteractiveMovement
// Support for reordering
@available(iOS 9.0, *)
open func beginInteractiveMovementForItem(at indexPath: IndexPath) -> Bool // returns NO if reordering was prevented from beginning - otherwise YES

@available(iOS 9.0, *)
open func updateInteractiveMovementTargetPosition(_ targetPosition: CGPoint)

@available(iOS 9.0, *)
open func endInteractiveMovement()

@available(iOS 9.0, *)
open func cancelInteractiveMovement()
复制代码

参考博客:

iOS UICollectionView高级用法(长按自由移动cell)-新app

4、瀑布流

实现瀑布流的基本原理找到最短的列,而后把item放到最短的列下面异步

以下图所示,因为第三列最短,因此第八个Item添加到第三列下面。oop

既然要找到 最短的列 ,则就须要用一个数据来保存每一列的Y值,推荐 数组 (相对来讲性能比 字典 好)。XRWaterfallLayout使用 字典 来存储,相比较 数组 的下标直接获取列的高度, 字典 多作了部分哈希操做。作瀑布流,图片的尺寸就多是不固定的,图片的尺寸能够服务器提早返回,而后cell直接设置大小。post

主要须要重写三个系统方法:详情参考实现:XRWaterfallLayout 一、- (void)prepareLayout 二、- (CGSize)collectionViewContentSize 三、- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

5、浮动的Header

1、在iOS9

UICollectionView的头部视图也能像tableViewheader同样出现悬浮挂住的效果。

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; 
//header 
flowLayout.sectionHeadersPinToVisibleBounds = YES; 
//footer
flowLayout.sectionFootersPinToVisibleBounds = YES;
复制代码

2、在iOS9.0

须要自定义UICollectionViewFlowLayout

#import <UIKit/UIKit.h>
@protocol LZSFloatHeaderFlowLayoutDelegate <NSObject>
-(void)sectionDidFloat:(NSInteger)section;
@end

@interface LZSFloatHeaderFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, weak) id<LZSFloatHeaderFlowLayoutDelegate> mDelegate;
@end
复制代码
#import "LZSFloatHeaderFlowLayout.h"

@interface LZSFloatHeaderFlowLayout()
@property (nonatomic, strong) NSMutableDictionary<NSNumber*, NSNumber*>* mSectionOffsetYDic;
@end

@implementation LZSFloatHeaderFlowLayout
-(NSMutableDictionary<NSNumber *,NSNumber *> *)mSectionOffsetYDic {
    if ( !_mSectionOffsetYDic ) {
        _mSectionOffsetYDic = [NSMutableDictionary dictionary];
    }
    return _mSectionOffsetYDic;
}
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    NSMutableIndexSet *missingSections = [NSMutableIndexSet indexSet];
    for (NSUInteger idx=0; idx<[answer count]; idx++) {
        UICollectionViewLayoutAttributes *layoutAttributes = answer[idx];
        if (layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) {
            [missingSections addIndex:layoutAttributes.indexPath.section];  // remember that we need to layout header for this section
        }
        if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
            [answer removeObjectAtIndex:idx];  // remove layout of header done by our super, we will do it right later
            idx--;
        }
    }
    // layout all headers needed for the rect using self code
    [missingSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];
        UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                                  atIndexPath:indexPath];
        [answer addObject:layoutAttributes];
    }];
    return answer;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind
                                                                     atIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForSupplementaryViewOfKind:kind
                                                                                         atIndexPath:indexPath];
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionView * const cv = self.collectionView;
        CGPoint const contentOffset = cv.contentOffset;
        CGPoint nextHeaderOrigin = CGPointMake(INFINITY, INFINITY);
        
        if (indexPath.section+1 < [cv numberOfSections]) {
            NSIndexPath* tIndexPath = [NSIndexPath indexPathForItem:0 inSection:indexPath.section+1]
            UICollectionViewLayoutAttributes *nextHeaderAttributes = [super layoutAttributesForSupplementaryViewOfKind:kind
                                                                                                           atIndexPath:tIndexPath];
            nextHeaderOrigin = nextHeaderAttributes.frame.origin;
        }
        CGRect frame = attributes.frame;
        if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
            frame.origin.y = MIN(MAX(contentOffset.y, frame.origin.y), nextHeaderOrigin.y - CGRectGetHeight(frame));
        }
        else { // UICollectionViewScrollDirectionHorizontal
            frame.origin.x = MIN(MAX(contentOffset.x, frame.origin.x), nextHeaderOrigin.x - CGRectGetWidth(frame));
        }
        attributes.zIndex = 1024;
        attributes.frame = frame;
        if ( self.mSectionOffsetYDic[@(indexPath.section)] && (self.mSectionOffsetYDic[@(indexPath.section)].integerValue != frame.origin.y) ) {
            if ( [self.mDelegate respondsToSelector:@selector(sectionDidFloat:)] ) {
                [self.mDelegate sectionDidFloat:indexPath.section];
            }
        }
        self.mSectionOffsetYDic[@(indexPath.section)] = @(frame.origin.y);
    }
    return attributes;
}
- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingSupplementaryElementOfKind:(NSString *)kind
                                                                                        atIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:kind
                                                                                        atIndexPath:indexPath];
    return attributes;
}
- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingSupplementaryElementOfKind:(NSString *)kind
                                                                                         atIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:kind
                                                                                        atIndexPath:indexPath];
    return attributes;
}
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound {
    return YES;
}
复制代码
相关文章
相关标签/搜索