在使用了
- collectionView: viewForSupplementaryElementOfKind: atIndexPath:
的 UICollectionView 页面中,滑动页面的时候滚动条会被 HeaderView 遮挡。致使滚动条看起来是断断续续的。swift
问题页面以下图所示(查看滚动条):app
以上问题具体是否与使用了 - collectionView: viewForSupplementaryElementOfKind: atIndexPath:
有关目前还不肯定,待验证。ui
这个问题在以前的 iOS 10 上是没有的,iOS 11 新出以后才出现。通过在 stackoverflow 上查找以后找到解决办法。https://stackoverflow.com/questions/46694144/scrollbar-incorrectly-appears-underneath-uicollectionview-section-headeratom
stackoverflow 中提供的是 swift 中的解决办法,我本身则使用的是 Objective-C。code
提示:解决这个问题只是更改了继承自
UICollectionReusableView
的自定义 HeaderView 类文件,因此这里只贴该自定义 HeaderView 的代码。继承
先看看在修复问题以前的 CustomHeaderView 类文件代码图片
// CustomHeaderView.h #import <UIKit/UIKit.h> extern NSString *const CustomHeaderViewReuseIdentifier; @interface CustomHeaderView : UICollectionReusableView @property (nonatomic, strong) UILabel *titleLabel; @end // CustomHeaderView.m #import "CustomHeaderView.h" NSString *const CustomHeaderViewReuseIdentifier = @"CustomHeaderView"; @implementation CustomHeaderView - (void)layoutSubviews { [super layoutSubviews]; [self createSubViews]; } - (void)createSubViews { _titleLabel = [[UILabel alloc] init]; _titleLabel.textColor = [UIColor blackColor]; CGFloat height = self.frame.size.height; _titleLabel.frame = CGRectMake(15, 0, 100, height); [self addSubview:_titleLabel]; } @end
当为以上代码的时候,APP 在 iOS11 上运行就会出现上图的问题。 根据 stackoverflow 的提示更改代码以后,该问题便被修复。get
如下为修复以后的CustomHeaderView类文件代码it
// CustomHeaderView.h #import <UIKit/UIKit.h> extern NSString *const CustomHeaderViewReuseIdentifier; #ifdef __IPHONE_11_0 @interface CustomLayer : CALayer @end #endif @interface CustomHeaderView : UICollectionReusableView @property (nonatomic, strong) UILabel *titleLabel; @end // CustomHeaderView.m #import "CustomHeaderView.h" NSString *const CustomHeaderViewReuseIdentifier = @"CustomHeaderView"; #ifdef __IPHONE_11_0 @implementation CustomLayer - (CGFloat) zPosition { return 0; } @end #endif @implementation CustomHeaderView - (void)layoutSubviews { [super layoutSubviews]; [self createSubViews]; } - (void)createSubViews { _titleLabel = [[UILabel alloc] init]; _titleLabel.textColor = [UIColor blackColor]; CGFloat height = self.frame.size.height; _titleLabel.frame = CGRectMake(15, 0, 100, height); [self addSubview:_titleLabel]; } #ifdef __IPHONE_11_0 + (Class)layerClass { return [CustomLayer class]; } #endif @end
以上代码相对于以前有问题的代码只是多了 #ifdef __IPHONE_11_0 ... #endif
之间的内容,使用 #ifdef __IPHONE_11_0 ... #endif
母的是防止更改以后的代码在 iOS 10 上出现问题,从而确保更改只是针对 iOS11 及以后的版本有效。io
更改以后的效果图以下所示: