UICollectionReusableView的用法,類似UITableView的分組

代碼如下:

//註冊
    [self.cv registerClass:[HybReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        HybReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        [reusableView.moreBtn setTitle:@"更多>" forState:UIControlStateNormal];
        [reusableView.moreBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        reusableView.moreBtn.frame = CGRectMake(SWIDTH - 50, 15, 50, 20);
        NSDictionary *dict = [_array objectAtIndex:indexPath.section];
        reusableView.label.frame = CGRectMake(5, 15, 100, 20);
        if (indexPath.section == 0) {
            reusableView.label.frame = CGRectMake(5, 210, SWIDTH, 40);
            reusableView.moreBtn.frame = CGRectMake(SWIDTH - 50, 220, 50, 20);
        }
        [reusableView.label setText:[dict objectForKey:@"recname"]];
        
        reusableView.label.font = [UIFont systemFontOfSize:15];
        reusableView.moreBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [reusableView.moreBtn addTarget:self action:@selector(moreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return reusableView;
    }
    return nil;
}

另外需要先創建一個繼承自UICollectionReusableView的類


#import <UIKit/UIKit.h>

@interface HybReusableView : UICollectionReusableView
@property (strong,nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIButton *moreBtn;
- (void) setLabelText:(NSString *)text;
@end

#import "HybReusableView.h"

@implementation HybReusableView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.label = [[UILabel alloc] init];
        self.moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.label.font = [UIFont systemFontOfSize:18];
        [self addSubview:self.label];
        [self addSubview:self.moreBtn];
    }
    return self;
}

- (void) setLabelText:(NSString *)text
{
    self.label.text = text;
    [self.label sizeToFit];
}
- (void)awakeFromNib {
    // Initialization code
}

@end


效果如圖






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章