自定义uitableviewcell,层层封装

封装,好处:减少viewcontroller累里的代码量,方便后期维护

cell:

.h

1 #import <UIKit/UIKit.h>
2 @class HMStatusFrame;
3 
4 @interface HMStatusCell : UITableViewCell
5 + (instancetype)cellWithTableView:(UITableView *)tableView;

.m

 1 @interface HMStatusCell()
 2 @property (nonatomic, weak) HMStatusDetailView *detailView;
 3 @property (nonatomic, weak) HMStatusToolbar *toolbar;
 4 @end
 5 
 6 @implementation HMStatusCell
 7 
 8 + (instancetype)cellWithTableView:(UITableView *)tableView
 9 {
10     static NSString *ID = @"status";
11     HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
12     if (!cell) {
13         cell = [[HMStatusCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
14     }
15     return cell;
16 }
17 
18 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
19 {
20     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
21     if (self) { // 初始化子控件
22         // 1.添加微博具体内容
23         HMStatusDetailView *detailView = [[HMStatusDetailView alloc] init];
24         [self.contentView addSubview:detailView];
25         self.detailView = detailView;
26         
27         // 2.添加工具条
28         HMStatusToolbar *toolbar = [[HMStatusToolbar alloc] init];
29         [self.contentView addSubview:toolbar];
30         self.toolbar = toolbar;
31         
32         // 3.cell的设置
33         self.backgroundColor = [UIColor clearColor];
34     }
35     return self;
36 }

  viewcontroller使用:

1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
2 {
3     HMStatusCell *cell = [HMStatusCell cellWithTableView:tableView];
4     
5     cell.statusFrame = self.statusFrames[indexPath.row];
6     
7     return cell;
8 }
IOS开发
原文地址:https://www.cnblogs.com/luanmage/p/4642054.html