我正在以编程方式打印标签,但我无法将其从屏幕上删除。我尝试了removeFromSuperview
和lbl1.hidden = YES;
以及lbl1= nil;
,但没有使用它们。它始终保留在屏幕上,而我可以在调试中看到它从ELSE
传递,如下面的代码所示。
我的问题在哪里?
-(void)reloadData
lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)];
if (result1 > result2 && al == YES)
{
lbl1.userInteractionEnabled = YES;
lbl1.text = @" Warning!! ";
lbl1.tag = 30;
lbl1.font = [UIFont fontWithName:@"Helvetica" size:18.0];
lbl1.textColor = [UIColor redColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.lineBreakMode = NSLineBreakByWordWrapping;
lbl1.numberOfLines = 2;
[self addSubview:lbl1];
[lbl1 release];
}
else{
//Non of them is removing the label.
[lbl1 removeFromSuperview];
lbl1= nil;
lbl1.hidden = YES;
}
答案 0 :(得分:4)
每次进入reloadData时,都会创建一个新标签,所以如果你重新加载并跳转到else,你就会创建一个标签,然后将其删除。
您需要将该标签保存为实例变量并将其删除/添加到reloadData中。
@property(nonatomic, strong) UILabel *lbl1;
在您的代码中,仅执行此操作:
self.lbl1 = [[[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)] autorelease];
在你的reloadData中执行:
-(void)reloadData
lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)];
if (result1 > result2 && al == YES)
{
self.lbl1.userInteractionEnabled = YES;
//Etc...
}
else{
[self.lbl1 removeFromSuperview];
}
答案 1 :(得分:1)
试试这样:
-(void)reloadData
if(!lbl1)
lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)];
if (result1 > result2 && al == YES)
{
lbl1.userInteractionEnabled = YES;
lbl1.text = @" Warning!! ";
lbl1.tag = 30;
lbl1.font = [UIFont fontWithName:@"Helvetica" size:18.0];
lbl1.textColor = [UIColor redColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.lineBreakMode = NSLineBreakByWordWrapping;
lbl1.numberOfLines = 2;
[self addSubview:lbl1];
[lbl1 release];
}
else{
//Non of them is removing the label.
[lbl1 removeFromSuperview];
lbl1= nil;
lbl1.hidden = YES;
}
答案 2 :(得分:0)
尝试像这样删除....
if (result1 > result2 && al == YES)
{
lbl1.userInteractionEnabled = YES;
lbl1.text = @" Warning!! ";
lbl1.tag = 30;
lbl1.font = [UIFont fontWithName:@"Helvetica" size:18.0];
lbl1.textColor = [UIColor redColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.lineBreakMode = NSLineBreakByWordWrapping;
lbl1.numberOfLines = 2;
[self addSubview:lbl1];
[lbl1 release];
}
else{
//Non of them is removing the label.
[[self.view viewWithTag:30] removeFromSuperview];
lbl1= nil;
lbl1.hidden = YES;
}