标签拒绝使用[label setHidden:YES]消失;在if方法中命令?

时间:2012-10-21 21:35:20

标签: iphone ios uitableview uilabel

我正在尝试在我的IOS应用中自定义我的tableView。当我的tableView(或更确切地说是数组)为空时,我想显示一个自定义标签而不是tableView中的项目。我指的标签是“label0”。但有些事情是非常错误的,我的[label0 setHidden:YES];或[label0 setHidden:NO];只适用于if“方法”的第一个块?在第二个块(如果没有),无论我尝试将标签设置为(隐藏或显示),都没有任何反应。

我错过了什么?我看不出自己的错?

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,     tableView.bounds.size.width, 30)] autorelease];
UILabel *label0 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 25,  tableView.bounds.size.width - 0, 100)] autorelease];

if ([self.searchResults count] == 0){

headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"lista2.png"]];

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(5, 3, tableView.bounds.size.width - 5, 18)] autorelease];
label.text = @"Information";
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];

 label0.text = @"Test test test";
  label0.textColor = [UIColor blackColor];
 label0.backgroundColor = [UIColor whiteColor];
 [tableView addSubview:label0];
  [label0 setHidden:NO];

 }

 else {

headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"lista2.png"]];

UILabel *label2 = [[[UILabel alloc] initWithFrame:CGRectMake(5, 3, tableView.bounds.size.width - 5, 18)] autorelease];
label2.text = @"Search results";
label2.textColor = [UIColor whiteColor];
label2.backgroundColor = [UIColor clearColor];
[headerView addSubview:label2];
[label0 setHidden:YES];       

}

 return headerView;
}

修改

我已将代码移至viewDidLoad并设置UILabel的属性。遗憾的是,这并没有解决我的问题......

UILabel *label0 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 25,    tableView.bounds.size.width - 0, 100)] autorelease];
[tableView addSubview:label0];

   if ([self.searchResults count] == 0){

       label0.text = @"Test test test";
       label0.textColor = [UIColor blackColor];
       label0.backgroundColor = [UIColor whiteColor];
       [label0 setHidden:NO];
   }
   else {
      [label0 setHidden:YES];
   }

3 个答案:

答案 0 :(得分:0)

这是因为每次调用此方法时都会创建label0,因此在“else”中您指的是完全不同的对象(不是在数组为空时添加到tableView的对象)。

您不应该从此方法向tableView添加子视图。考虑使用viewDidLoad。这样你只需要添加一次label0。要实现这一点,请将label0添加为viewController的属性。

答案 1 :(得分:0)

您忘记将label0添加为子视图,请将此行放在else语句

 [tableView addSubview:label0];

我也看不到这样做有什么好处。我相信你可以隐藏表视图并显示另一个带有标签的视图。但是当你在1个月后回来调试这段代码时,你会很难理解它,那么嵌套视图并不好。

答案 2 :(得分:0)

你在编辑中说你为UILabel设置了属性(我假设你的意思是你有一个名为label0的属性?)。如果是这样,那么当你为你的标签分配init时,它应该是self.label0 = ..... not UILabel * label0 = .....