我正在尝试在iOS应用程序中自定义我的tableview。当我的tableView(或更确切地说的数组)为空时,我想显示自定义的标签,而不是表视图中的项目。我指的标签是" Label0"。但是我的[label0 sethidden:是];或[label0 sethidden:no];仅在"方法"的第一个块中工作?在第二个块中(如果是其他),无论我尝试将标签设置为(隐藏或显示)。
我错过了什么?我看不到自己的错?
- (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;
}
编辑
我已经将代码移动到查看迪德载并设置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];
}
这是因为每当此方法称为" else"时,您都会引用完全不同的对象(而不是当数组为空时添加到tableView的对象时,都会创建您的label0。。
您不应该从此方法将子视图添加到tableView。考虑使用ViewDidload。这样,您将仅添加Label0一次。为了实现该添加标签0作为viewController的属性。
您忘了添加label0
作为子视图
[tableView addSubview:label0];
我也看不到任何好处。我相信您可以隐藏表视图并显示具有标签的另一个视图。但是,当您回到1个月后回来调试此代码时,嵌套视图不好。
您在编辑中说您为Uilabel设置了属性(我认为您的意思是您有一个称为Label0的属性?)。如果是这样,那么当您alloc启动您的标签时,应该是self.label0 = .....不是uilabel *label0 = .....