#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZEmptyTableViewHeaderFooterView : UITableViewHeaderFooterView
@property(nonatomic, strong) UIColor *bgColor;
@end
NS_ASSUME_NONNULL_END
#import "ZEmptyTableViewHeaderFooterView.h"
@implementation ZEmptyTableViewHeaderFooterView
-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
if(self = [super initWithReuseIdentifier: reuseIdentifier]) {
self.bgColor = [UIColor clearColor];
}
return self;
}
-(void)layoutSubviews {
[super layoutSubviews];
//⚠️放在这里修改是因为在iOS12时,backgroundView并不会在初始化时创建
self.backgroundView.backgroundColor = self.bgColor;
}
-(void)setBgColor:(UIColor *)bgColor {
_bgColor = bgColor;
self.backgroundColor = bgColor;
self.contentView.backgroundColor = bgColor;
self.backgroundView.backgroundColor = bgColor;
if (@available(iOS 14.0, *)) {
self.backgroundConfiguration = UIBackgroundConfiguration.clearConfiguration;
} else {
// Fallback on earlier versions
}
}
注意:在iOS 12以上,初始化时更改backgroundView的背景色有效,以下则无效,关键问题,测试时发现在初始化调用时,backgroundView视为nil,所以修改无效,因为我不清楚backgroundView的创建时机,为确保更改有效,所以我暂时放在layoutSubviews中进行修改,这是因为在调用addSubview时,必然会调用layoutSubviews。
如果有大神能确认backgroundView的创建时机,望不吝告知,感谢!!!