您的位置:首页 > 移动开发 > IOS开发

ios-表视图-demo-自定义cell和心得

2014-04-28 21:39 381 查看
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *cellindentifier=@"cell";

if (self.celltype==KTableViewCellContenview) {//第一种自定义cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellindentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellindentifier];
UILabel*lable= [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];//在这里创建性能更高,最少的创建实例滑动的时候
lable.tag=101;
[cell.contentView addSubview:lable];
}
UILabel * lable=(UILabel *) [cell.contentView viewWithTag:101];
lable.text=_dataarray[indexPath.row];
lable.font=[UIFont fontWithName:_dataarray[indexPath.row] size:16];
return cell;

}else if(self.celltype==KTableViewCellCustom){

MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellindentifier];
if (cell==nil) {
cell=[[MyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellindentifier];
NSLog(@"排版前%d",indexPath.row);
}

return cell;

}else if(self.celltype==KTableViewCellNib){//从nib来
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellindentifier];
if (cell==nil) {
NSArray*nibs=[[NSBundle mainBundle]loadNibNamed:@"MyCell" owner:self options:nil];
cell=[nibs objectAtIndex:0];
}
UILabel * lable=(UILabel *) [cell.contentView viewWithTag:102];
lable.text=_dataarray[indexPath.row];
lable.font=[UIFont fontWithName:_dataarray[indexPath.row] size:16];
return cell;

}else{

return nil;
}

}


首先是对我们为什么自定义系统的cell尺寸没用,因为ios会在我们创建了一屏幕的cell的时候会调用
-(void)layoutSubviews{
[super layoutSubviews];
self.textlabel.frame=CGRectMake(0, 0, 300, 44);
}
对创建了的cell进行重新排版,当然这里的重新排版只会对contentview以外的进行排版,以后滑动屏幕的时候,可能是新建立的cell或者重用的都会进行排版,
想要对contentview进行手动排版的话可以手动来覆写
-(void)layoutSubviews{
[super layoutSubviews];
//在这里写,比如下面这个文件这样
}


//
//  MyCell.m
//  CustomCellDemo
//
//  Created by  liyang on 14-4-28.
//  Copyright (c) 2014年 liyang. All rights reserved.
//

#import "MyCell.h"

@implementation MyCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_label=[[UILabel alloc]initWithFrame:CGRectZero];
_label.backgroundColor=[UIColor orangeColor];
[self.contentView addSubview:_label];
}
return self;
}
-(void)layoutSubviews{
[super layoutSubviews];
_label.frame=CGRectMake(0, 0, 300, 44);
NSLog(@"排版后%d");
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: