在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 ???
}
}发布于 2014-01-07 09:27:52
看看这个问题,第二个答案给出了一个很好的描述。
简而言之,您不应该使用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");
}
}
}这不是一个很好的解决方案,我个人会做一些事情,比如让这个自定义的单元格保持一个布尔值,然后切换它的状态并检查它。但这取决于你的发展,这是它应该如何工作的一般想法。
编辑2:
由于您决心在didSelectRowAtIndexPath中运行它,并且完全无法进行任何级别的研究或将任何精力投入到您的工作中,所以我建议您使用以下方法:
tableView cellForRowAtIndexPath:<#(NSIndexPath *)#>发布于 2014-01-07 09:32:08
它可以在类中添加表视图委托。
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath
*)indexPath
{
if((indexPath.row)==0) {
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"normal.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
yourcustomcell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"pressed.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
or
cell.backgroundView = nil;
[tableview reloadData];
}https://stackoverflow.com/questions/20967896
复制相似问题