UITableVIew程序员iOS Developer

UIVIewHeadFootorView 重用

2016-03-24  本文已影响234人  司马捷

1.自定义一个UITableViewHeaderFooterView 子类:ERReadHeaderFooterView
效果如下:


D8297087-1D0E-4615-A526-BE0BF7B8A602.PNG

2.添加内部属性

@interface ERReadHeaderFooterView ()

@property(nonatomic,weak)UIView *bootomLineView;
@property(nonatomic,weak)UIImageView *indictorView;
@property(nonatomic,weak)UILabel *titleLabel;
@end

3.实现Impemention 重写-(instancetype)initWithFrame:(CGRect)frame,
注意:使用下面方法进行初始化在iphone6之前都会调用-(instancetype)initWithFrame:(CGRect)frame{}方法

headView = [[ERReadHeaderFooterView alloc]initWithReuseIdentifier:headViewId];

最后建议重写

-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier{

self = [super initWithReuseIdentifier:reuseIdentifier];
if (self) {
    
   [self setupSubView];
    self.frame = CGRectMake(0, 0, KSrceenWidth, KERReadHeaderFooterViewH);
}

return self;

}

这个方法在iphone6之后就没有被调了.

-(instancetype)initWithFrame:(CGRect)frame{

self = [super initWithFrame:frame];

if (self) {
    [self setupSubView];
    self.frame = CGRectMake(0, 0, KSrceenWidth, KERReadHeaderFooterViewH);
}
return self;
}

-(void)setupSubView{
UIView *bootomLineView = [[UIView alloc]init];
bootomLineView.backgroundColor = [UIColor blackColor];
bootomLineView.alpha = 0.2;
[self.contentView addSubview:bootomLineView];
self.bootomLineView = bootomLineView;


UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"me_more"]];
[self.contentView addSubview:imageView];
self.indictorView = imageView;
UILabel *titleLabel = [[UILabel alloc]init];

[self.contentView addSubview:titleLabel];
_titleLabel = titleLabel;

}

4.重写LayoutSubview方法
重写layoutSubview的时候,注意self的frame.
对于什么时候调用LayoutSubviews,要注意相关链接:
http://blog.csdn.net/meegomeego/article/details/39890385

-(void)layoutSubviews{

[super layoutSubviews];
CGFloat lineH = 0.5;
CGFloat lineW = self.width;
self.bootomLineView.frame = CGRectMake(15, self.height-lineH, lineW, lineH);

 //  CGFloat indorH = 20;
CGFloat indorW = 20;
CGFloat indorTop = 11;
self.indictorView.right = KSrceenWidth -10;
self.indictorView.top = indorTop;
self.indictorView.size = CGSizeMake(indorW, self.height-2*indorTop);

CGFloat textW = 200;
CGFloat textH = 20;
self.titleLabel.frame = CGRectMake(0, 0, textW, textH);

}

5.在ViewController中使用 需要提前注册

[self.tableView registerClass:[ERReadHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headViewId];

开始调用

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//UITableViewHeaderFooterView
//  return nil
ERReadHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headViewId];

if (headView == nil) {
    
    headView = [[ERReadHeaderFooterView alloc]initWithReuseIdentifier:headViewId];
}
return headView;

}
上一篇 下一篇

猜你喜欢

热点阅读