//注册头视图
[self.catecollection registerNib:[UINib nibWithNibName:xibname bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:identifier];
// 返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//如果是头视图
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:Identifier forIndexPath:indexPath];
for(UIView *view in header.subviews){
[view removeFromSuperview];
}
//头视图添加view
[header addSubview:self.headerView];
return header;
}
return nil;
}
懒加载头部试图
- (SsLeaderHeaderVIew *)headerView
{
if(!_headerView)
{
_headerView.backgroundColor=[UIColor whiteColor];
_headerView =[SsLeaderHeaderVIew xibSsLeaderHeaderVIew];
_headerView.leaderdelegate=self;
}
return _headerView;
}
头部视图类
SsLeaderHeaderVIew.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SsLeaderHeaderVIewDelegate <NSObject>
-(void)clickLeader;
@end
//这里着重注意collectionview的头部视图需要继承UICollectionReusableView,在注册头部视图的时候用到,否则注册失败程序崩溃。
@interface SsLeaderHeaderVIew : UICollectionReusableView
@property (nonatomic,strong) id<SsLeaderHeaderVIewDelegate>leaderdelegate;
@property (weak, nonatomic) IBOutlet UIImageView *SsLeaderImage;
@property (weak, nonatomic) IBOutlet UILabel *SsLeaderName;
+(instancetype)xibSsLeaderHeaderVIew;
@end
NS_ASSUME_NONNULL_END
SsLeaderHeaderVIew.m
#import "SsLeaderHeaderVIew.h"
@implementation SsLeaderHeaderVIew
+(instancetype)xibSsLeaderHeaderVIew{
return (SsLeaderHeaderVIew *)[[[NSBundle mainBundle] loadNibNamed:@"SsLeaderHeaderView" owner:self options:nil] lastObject];
}
- (IBAction)ChooseLeader:(id)sender {
if (_leaderdelegate && [_leaderdelegate respondsToSelector:@selector(clickLeader)]) {
[_leaderdelegate clickLeader];
}
}
- (IBAction)ChooseLeaderSame:(id)sender {
if (_leaderdelegate && [_leaderdelegate respondsToSelector:@selector(clickLeader)]) {
[_leaderdelegate clickLeader];
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
网友评论