自定义cell步骤:
1: 创建一个继承自UITableViewCell的类
2: 重写初始化方法
3: 在初始化方法中, 把需要的视图加到self.contentView上面
4: 去返回cell的方法中, 把系统的 UITableViewCell 替换成你自己创建的类
例如:
音乐播放器中, 需要单独的自定义cell
来存放歌词,
歌词放在label中
创建类 LyricCell , 声明需要的属性label
#import <UIKit/UIKit.h>
@interface LyricCell : UITableViewCell
@property (nonatomic, retain) UILabel *label;
@end
重写初始化
#import "LyricCell.h"
@implementation LyricCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self addCellSubViews]; // 调用
}
return self;
}
// 添加
- (void)addCellSubViews
{
// 添加label和cell大小一样
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
self.label.backgroundColor = [UIColor redColor];
[self.contentView addSubview:self.label];
}
回到创建cell的控制器中, 改成自己定义的 LyricCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"GGCell";
LyricCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; //这里一处
if (cell == nil) {
cell = [[LyricCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier]; // 这里一处
}
NSString *string = self.dataArray[indexPath.row];
NSString *str = [string substringFromIndex:11];
cell.label.text = str; // label前加 cell.
return cell;
}
over