0

I am trying to customize my tableView in my IOS app. When my tableView(or rather array) is empty, I want to display a customized label instead of the items in the tableView. The label I am referring to is "label0". But something is terribly wrong, my [label0 setHidden:YES]; or [label0 setHidden:NO]; only works in the first block of the if "method"? In the second block (if else) nothing happens no matter what I try to set the label as (hidden or shown).

What have I missed? I cannot see my own fault?

- (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;
}

EDIT

I have moved the code to viewDidLoad and set the property for the UILabel. This have unfortunately not solved my problem....

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];
   }
4

3 回答 3

0

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

 [tableView addSubview:label0];

我也看不出这样做有什么好处。我相信您可以隐藏表格视图并显示另一个具有标签的视图。但是以这种方式嵌套视图并不好,当您在 1 个月后回来调试此代码时,您将很难理解它。

于 2012-10-21T21:44:43.697 回答
0

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

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

于 2012-10-21T21:37:56.043 回答
0

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

于 2012-10-21T23:56:07.283 回答