我有 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 { ... }
从这里您可以根据需要自定义每个单元格的背景,只需在用户点击时重新加载该行即可。
How to customize the background color of a UITableViewCell?
编辑
现在因为您添加了代码,所以我可以清楚地看到问题所在:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"BTSTicketsCellIdentifier";
CRHomeCategCell *cell = (CRHomeCategCell *)[_tblCateg dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundView = nil;
}
这并不像你想象的那样。 dequeueReusableCellWithIdentifier:CellIdentifier
为您提供一个新的单元格实例,该实例基于标识符标识的单元格。
您没有在此处获得对该行的引用,您正在创建一个新行并将其背景设置为零。
你的代码应该更像这样:
- (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");
}
}
}
这不是一个很好的解决方案,我个人会做一些更像让这个自定义单元格保存 bool 值并切换其状态并检查的事情。但这取决于您的开发,这是它应该如何工作的总体思路。
编辑2:
既然您决定在 didSelectRowAtIndexPath
中运行它,并且完全无法进行任何级别的研究或为您的工作投入任何精力,我可能建议您使用以下方法:
tableView cellForRowAtIndexPath:<#(NSIndexPath *)#>
关于ios - 隐藏取消隐藏 UITableViewCell 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20967896/