我UITableView
在其中要在第一个单元格上viewDidLoad
添加图像后,在方法中的第一个单元格上添加背景图像,当用户选择任何其他行时,我想隐藏我的背景图像。
有可能吗?
请帮助并提前致谢。
编辑:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
if(indexPath.row==0){
cell.backgroundView = [ [UIImageView alloc] initWithImage:[[UIImage imageNamed:@"active-tab.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
flag=true;
NSLog(@"willDisplayCell");
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (flag==true) {
cell.backgroundView = nil; //How to get `cell` here ?
//How to remove BGImage from first cell ???
}
}
看一下这个问题,第二个答案给出了很好的描述。
简而言之,您不应使用viewDiLoad
回调,而应使用
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }
在这里,您可以根据需要自定义每个单元格的背景,只需在用户单击时重新加载行即可。
编辑
现在,因为您添加了代码,所以我可以清楚地看到问题所在:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"BTSTicketsCellIdentifier";
CRHomeCategCell *cell = (CRHomeCategCell *)[_tblCateg dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundView = nil;
}
这并没有您认为的那样。dequeueReusableCellWithIdentifier:CellIdentifier
根据标识符标识的单元格,为您提供一个新的单元格实例。
您在此处没有对该行的引用,而是在创建一个新行并将其背景设置为nil。
您的代码应该更像这样:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
if(indexPath.row==0){
if(cell.backgroundView == nil)
{
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"active-tab.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
NSLog(@"willDisplayCell");
}
else
{
cell.backgroundView = nil;
NSLog(@"willHideCell");
}
}
}
这不是一个很好的解决方案,我个人会做更多的事情,例如让这个自定义单元格保持一个布尔值并切换其状态并检查。但这取决于您的发展,这是它应该如何工作的总体思路。
编辑2:
由于您确定要在内部运行它,didSelectRowAtIndexPath
并且完全不能进行任何级别的研究或对您的工作进行任何努力,因此我建议使用以下方法:
tableView cellForRowAtIndexPath:<#(NSIndexPath *)#>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句