iOS 11 下 UICollectionView 出現(xiàn)滾動條被 HeaderView 遮擋的問題
在使用了
- collectionView: viewForSupplementaryElementOfKind: atIndexPath:
的 UICollectionView 頁面中总寒,滑動頁面的時候滾動條會被 HeaderView 遮擋。導(dǎo)致滾動條看起來是斷斷續(xù)續(xù)的鲤桥。
問題頁面如下圖所示(查看滾動條):

以上問題具體是否與使用了 - collectionView: viewForSupplementaryElementOfKind: atIndexPath:
有關(guān)目前還不確定蚯嫌,待驗(yàn)證芽淡。
這個問題在之前的 iOS 10 上是沒有的,iOS 11 新出之后才出現(xiàn)挣菲。經(jīng)過在 stackoverflow 上查找之后找到解決辦法富稻。https://stackoverflow.com/questions/46694144/scrollbar-incorrectly-appears-underneath-uicollectionview-section-header
stackoverflow 中提供的是 swift 中的解決辦法,我自己則使用的是 Objective-C白胀。
提示:解決這個問題只是更改了繼承自
UICollectionReusableView
的自定義 HeaderView 類文件椭赋,所以這里只貼該自定義 HeaderView 的代碼。
先看看在修復(fù)問題之前的 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
當(dāng)為以上代碼的時候哪怔,APP 在 iOS11 上運(yùn)行就會出現(xiàn)上圖的問題。
根據(jù) stackoverflow 的提示更改代碼之后认境,該問題便被修復(fù)。
以下為修復(fù)之后的CustomHeaderView類文件代碼
// 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
之間的內(nèi)容篷扩,使用 #ifdef __IPHONE_11_0 ... #endif
母的是防止更改之后的代碼在 iOS 10 上出現(xiàn)問題茉盏,從而確保更改只是針對 iOS11 及之后的版本有效鉴未。
更改之后的效果圖如下所示:
