自定义内容视图
step1:创建显示内容的视图
step2: 将这些视图以子视图的形式,添加到cell.contentView 中即可
3.自定义辅助视图
step1:创建视图
step2:将视图 赋值给 cell.accessoryView 即可
//
// MyTableViewController.m
//
#import "MyTableViewController.h"
@interface MyTableViewController ()
@end
@implementation MyTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
//为tableView 注册单元格类型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
/****** 自定义内容视图 **************/
UILabel *label = [cell.contentView viewWithTag:120];
if (label == nil){ //如果 cell中没有我们自己定义的 这个Label, 那么我就创建一个添加到cell中
label = [[UILabel alloc]init];
label.tag = 120;
label.frame = CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height);
label.font = [UIFont italicSystemFontOfSize:36];
label.textColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:label];
}
label.text = [NSString stringWithFormat:@"该行是 %ld行",indexPath.row];
/***** 自定义辅助视图 ****************/
if (indexPath.row == 2) {
UISwitch *myswitch = [[UISwitch alloc]init];
myswitch.on = YES;
[myswitch addTarget:self action:@selector(clickSwitch:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = myswitch;
}else {
cell.accessoryView = nil;
}
return cell;
}
-(void)clickSwitch:(UISwitch*)sender {
NSLog(@"当前是 %@ ", sender.on ? @"开" : @"关");
}
@end