【自定義Cell2】【Code】:所有經過代碼添加緩存
【1】:設置Cellatom
1):建立一個MsgCell類 繼承UITableViewCellurl
.h中聲明2個屬性一個是用戶頭像,另一個是發表的文字spa
@property (nonatomic,weak,readonly) UIImageView *iconView; @property (nonatomic,weak,readonly)UIButton *msgBtn;
.m中,建立出具體的cell內容code
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { // 添加子控件 1,左邊的頭像 UIImageView *iconView=[[UIImageView alloc] init]; iconView.frame=CGRectMake(10, 10, 50, 50); [self addSubview:iconView]; [self.contentView addSubview:iconView]; _iconView=iconView; // 添加右邊的對話按鈕 UIButton *btn=[[UIButton alloc]init]; btn.frame=CGRectMake(100, 0, 100, 60); [btn setBackgroundImage:[UIImage imageNamed:@"chatfrom_bg_normal.png"] forState:UIControlStateNormal]; [btn setBackgroundImage:[UIImage imageNamed:@"chatfrom_bg_focused.png"] forState: UIControlStateHighlighted]; [self.contentView addSubview:btn]; // 設置文字顏色 [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; _msgBtn=btn; } return self; }
建立一個ViewController:UITableViewControllerorm
#import "ViewController.h" #import "MsgCell.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 去除橫線 self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone; self.tableView.editing = YES; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 20; // 20個cell } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 用static修飾的局部變量,只會初始化一次 static NSString *ID=@"Cell"; // 2.拿到一個標識先去緩存池中查找對應的Cell MsgCell *cell=[tableView dequeueReusableCellWithIdentifier:ID]; // 3. 若是緩存池中沒有,才須要建立新的標識 if(cell==nil) { cell=[[MsgCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]; } cell.iconView.image=[UIImage imageNamed:@"0.png"]; [cell.msgBtn setTitle:@"哈哈哈" forState:UIControlStateNormal]; return cell; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 每一行的高度自定義 return 70; } @end