美文网首页iOS
iOS 11 下 UICollectionView 出现滚动条被

iOS 11 下 UICollectionView 出现滚动条被

作者: 濑鸽骑 | 来源:发表于2017-10-21 23:11 被阅读404次

iOS 11 下 UICollectionView 出现滚动条被 HeaderView 遮挡的问题

在使用了- collectionView: viewForSupplementaryElementOfKind: atIndexPath:的 UICollectionView 页面中,滑动页面的时候滚动条会被 HeaderView 遮挡。导致滚动条看起来是断断续续的。

问题页面如下图所示(查看滚动条):

以上问题具体是否与使用了 - collectionView: viewForSupplementaryElementOfKind: atIndexPath: 有关目前还不确定,待验证。

这个问题在之前的 iOS 10 上是没有的,iOS 11 新出之后才出现。经过在 stackoverflow 上查找之后找到解决办法。https://stackoverflow.com/questions/46694144/scrollbar-incorrectly-appears-underneath-uicollectionview-section-header

stackoverflow 中提供的是 swift 中的解决办法,我自己则使用的是 Objective-C。

提示:解决这个问题只是更改了继承自 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 的提示更改代码之后,该问题便被修复。

以下为修复之后的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之间的内容,使用 #ifdef __IPHONE_11_0 ... #endif母的是防止更改之后的代码在 iOS 10 上出现问题,从而确保更改只是针对 iOS11 及之后的版本有效。

更改之后的效果图如下所示:

相关文章

网友评论

    本文标题:iOS 11 下 UICollectionView 出现滚动条被

    本文链接:https://www.haomeiwen.com/subject/hpiwuxtx.html