IOS ——UI篇—— 自定义UITableViewCell的方法

复制代码

MyTableViewCell.h文件

1
//自定义cell,在.h里进行控件属性的声明(注意要继承于:UITableViewCell) 2 #import <UIKit/UIKit.h> 3 4 @interface MyTableViewCell : UITableViewCell 5 6 @property (nonatomic, strong) UIImageView *newsImg; 7 @property (nonatomic, strong) UILabel *titleLabel; 8 @property (nonatomic, strong) UILabel *subLabel; 9 10 @end
复制代码
MyTableViewCell.m文件

复制代码
 1 //自定义cell,在.m里进行控件的初始化以及控件的布局(控件的Frame参数以设定的行高为基准)
 2 #import "MyTableViewCell.h"
 3 
 4 @implementation MyTableViewCell
 5 
 6 -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
 7     
 8     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
 9     if (self) {
10         _newsImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 100, 80)];
11         [self addSubview:_newsImg];
12         
13         _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 5, 200, 30)];
14         [self addSubview:_titleLabel];
15         
16         _subLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 55, 200, 30)];
17         [self addSubview:_subLabel];
18     }
19     return self;
20 }
21 
22 - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
23     [super setSelected:selected animated:animated];
24 
25     // Configure the view for the selected state
26 }
27 
28 @end
复制代码

 

这样就完成了UITableViewCell的自定义,在使用时就可以直接给自己定义的控件赋值,在自定义时可以设置这些控件的属性,达到不同的cell的效果;

 

自定义cell的使用(首先在使用的地方导入自定义cell的头文件)

复制代码
 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 2     
 3     static NSString *identifier = @"Cell";
 4     MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
 5     if (cell == nil) {
 6         cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
 7     }
 8     
 9     NewsInfo *_info = _array[indexPath.row];
10     
11     cell.newsImg.image = [UIImage imageNamed:_info.imageName];
12     
13     cell.titleLabel.text = _info.title;
14     cell.subLabel.text = _info.subTitle;
15     
16     return cell;
17     
18 }
复制代码

 

 

 




posted @   #零下一度&  阅读(289)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
点击右上角即可分享
微信分享提示