引言
- 制作网易云音乐demo时遇到了自定义Cell这个难关,到处搜博客,简书,愣是没学会,感觉都是铁憨憨写的。最后还是组长传授一波代码,学会了到底应该怎么写,因此我写这一篇博客,一定要让最萌的萌新(像我一样的)学会自定义Cell。
- 这篇不包括UITableView的操作,不知道的可以看这篇UITableView的常用方法,属性
教学
示例代码(方法一:不需要新建Cell文件)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell1 = [tableView
dequeueReusableCellWithIdentifier:@"cell1"];
if (cell1 == nil) {
cell1 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell1"];
UIButton *button = [[UIButton alloc] init];
button.backgroundColor = [UIColor whiteColor];
button.layer.masksToBounds = YES;
button.layer.borderWidth = 1;
button.layer.borderColor = [UIColor grayColor].CGColor;
button.frame = CGRectMake(235, 45, 70, 30);
button.layer.cornerRadius = 5;
button.tintColor = [UIColor whiteColor];
button.backgroundColor = [UIColor blueColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
imageNamed:@"金币"]forState:UIControlStateNormal];
[cell1.contentView addSubview:button];
}
return cell1;
}
心得体会
- 上面注释的1,2,3,4就是自定义Cell必须要有的几行代码,主要是因为cell的复用问题导致需要有这套格式,如果暂时不懂就先记住这5条吧
- 然后我在里面设置了一个Button按钮,当然你可以在里面放任何控件了,就和普通的没什么区别。其中注释6的这行代码不要忘记,不然Button不会显示。
- 这里面你就会发现,你使用了cell1设定了一类Cell,如果有多种cell的话,要挨个设置,显得很捞,这就是为什么我们一般采用第二种方法的原因。
示例代码(方法二:需要新建Cell文件,每一段代码在一个文件里)
#import <UIKit/UIKit.h>
@interface MusicTableViewCell : UITableViewCell
@property (nonatomic, strong) UIButton *icon1;
@property (nonatomic, strong) UILabel *label1;
@property (nonatomic, strong) UILabel *label2;
@property (nonatomic, strong) UILabel *label3;
@end
#import "MusicTableViewCell.h"
@implementation MusicTableViewCell
- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.icon1 = [[UIButton alloc] init];
[self.contentView addSubview:_icon1];
self.label1 = [[UILabel alloc] init];
[self.contentView addSubview:_label1];
self.label2 = [[UILabel alloc] init];
[self.contentView addSubview:_label2];
}
return self;
}
- (void) layoutSubviews {
[super layoutSubviews];
_icon1.frame = CGRectMake(0, 0, 55, 50);
_label1.frame = CGRectMake(65, 0, 200, 50);
_label2.frame = CGRectMake(100, 0, 70, 50);
}
- (void)awakeFromNib {
[super awakeFromNib];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)viewDidLoad {
[self.tableView registerClass:[MusicTableViewCell class] forCellReuseIdentifier:@"musicCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MusicTableViewCell* cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:@"musicCell"forIndexPath:indexPath];
cell.label1.text = @"xxxxxx";
return cell;
}
心得体会
- 其实和上一种差不多,主要就是在新建Cell文件里多了几步
- 在UIViewController里的操作和上一个差不多,就那几个注意点。其中[self.contentView addSubview:_icon1]这句话不是不要,是放在Cell.m里了。