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 }



感谢您的访问! 若对您有帮助或有兴趣请关注博客:http://www.cnblogs.com/Rong-Shengcom/
原文地址:https://www.cnblogs.com/Rong-Shengcom/p/4992070.html