IOS TableView Cell 选中状态

//懒加载

-(NSArray *)allColors {

if(_allColors==nil) {

_allColors=@[[UIColorredColor],[UIColorgreenColor],[UIColorblueColor]];

}

return_allColors;

}

- (void)viewDidLoad {

[superviewDidLoad];

self.selectIndex= -1;

}

- (void)didReceiveMemoryWarning {

[superdidReceiveMemoryWarning];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {

return1;

}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {

return50;

}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:@"reuseIdentifier"];

if(cell ==nil) {

cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"reuseIdentifier"];

staticintmyIndex =0;

myIndex++;

NSLog(@"%d",myIndex);

}

UILabel*label = [cell.contentViewviewWithTag:100];

if(label ==nil) {

//创建label并添加到cell的contentView

//自定义内容视图

label = [[UILabelalloc]init];

label.frame=CGRectMake(0,0, tableView.frame.size.width,60);

label.textAlignment=NSTextAlignmentCenter;

label.font= [UIFontsystemFontOfSize:36];

//将创建好的视图添加到cell的contentView

label.tag=100;

[cell.contentViewaddSubview:label];

}

label.text= [NSStringstringWithFormat:@"当前是第%ld行",indexPath.row];

//设置辅助视图

/*

UITableViewCellAccessoryDisclosureIndicator,UITableViewCellAccessoryDetailDisclosureButton UITableViewCellAccessoryCheckmark

UITableViewCellAccessoryDetailButton

*/

//cell.accessoryType = UITableViewCellAccessoryCheckmark;

if(indexPath.row!=self.selectIndex){

cell.accessoryType=UITableViewCellAccessoryNone;

}else{

cell.accessoryType=UITableViewCellAccessoryCheckmark;

}

returncell;

}

//默认单元格高度44,但是可以自己通过代理方法修改

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {

return60;

}

//一答

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(nonnullNSIndexPath*)indexPath {

//把选中的行号记录下来

self.selectIndex= indexPath.row;

//设置选中行的辅助视图

UITableViewCell*selectCell = [tableViewcellForRowAtIndexPath:indexPath];

selectCell.accessoryType=UITableViewCellAccessoryCheckmark;

}

//哪行被反选该如何处理

-(void)tableView:(UITableView*)tableView didDeselectRowAtIndexPath:(nonnullNSIndexPath*)indexPath {

//取出哪行cell被反选了

UITableViewCell*deselectCell = [tableViewcellForRowAtIndexPath:indexPath];

//设置被反选的cell的辅助视图

deselectCell.accessoryType=UITableViewCellAccessoryNone;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容