在使用了
- 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
更改以後的效果圖以下所示: