Ios 当视图出现时创建UILabel,当视图消失时销毁它

Ios 当视图出现时创建UILabel,当视图消失时销毁它,ios,objective-c,Ios,Objective C,对于我的应用程序教程,我试图创建一个UILabel,当视图出现时,它会在显示的屏幕上漂移,然后被销毁,这样,如果用户在教程中返回到该视图,UILabel将被重新创建,并在页面上漂移。以下是我使用UIPageViewController显示的其中一个自定义视图控制器的示例: //this is just a custom UILabel with some padding @property (nonatomic) PaddedLabel *directionsLabel; //I have t

对于我的应用程序教程,我试图创建一个UILabel,当视图出现时,它会在显示的屏幕上漂移,然后被销毁,这样,如果用户在教程中返回到该视图,UILabel将被重新创建,并在页面上漂移。以下是我使用UIPageViewController显示的其中一个自定义视图控制器的示例:

//this is just a custom UILabel with some padding
@property (nonatomic) PaddedLabel *directionsLabel;

//I have tried setting UILabel to nil or removing it from view
-(void)viewWillDisappear:(BOOL)animated
{

    NSLog(@"view is disappearing");
    //this does not remove the label
    self.directionsLabel = nil;
    //nor does this
    [self.directionsLabel removeFromSuperview];

}

- (void)viewDidAppear:(BOOL)animated
{
    [self messageTutorial];
}

- (void)messageTutorial
{

    CGFloat width = [[UIScreen mainScreen] bounds].size.width;
    CGFloat height = [[UIScreen mainScreen] bounds].size.height;
    PaddedLabel *directionsLabel = [[PaddedLabel alloc] initWithFrame:CGRectMake(_width/2, _height/2, 100, 100)];
    directionsLabel.text = @"test";

    CGRect f = directionsLabel.frame;
    f.size = size;
    directionsLabel.frame = f;
    directionsLabel.center = self.view.center;
    f = directionsLabel.frame;
    f = directionsLabel.frame;
    f.origin.y = .1*height;
    directionsLabel.frame = f;
    [self.view addSubview:directionsLabel];


   [UIView animateWithDuration:TUTORIAL_DISAPPEAR_TIME animations:^{
        directionsLabel.alpha = .5;
       CGRect f = directionsLabel.frame;
       f.origin.y = height - f.size.height*1.4;
       directionsLabel.frame = f;
       NSLog(@"animating");

    } completion:^(BOOL finished) {
        [directionsLabel removeFromSuperview];
        //this also doesn't actually remove the label

    }];


}
问题是,如果用户返回页面以查看此视图,她现在会看到一个新标签和一个旧标签,因此,如果您来回翻页,您最终会看到许多标签都在屏幕上显示相同的内容,处于不同的进展阶段

如何在视图消失时删除UILabel,并在视图出现/重新出现时添加/创建新标签


谢谢。

您的
视图中的代码将消失
方法是向后的。你需要:

- (void)viewWillDisappear:(BOOL)animated {
    NSLog(@"view is disappearing");
    [self.directionsLabel removeFromSuperview];
    self.directionsLabel = nil;
}
正如您所看到的,在尝试删除它之前,将
self.directionsLabel
设置为
nil
,将导致不操作


另外,在创建标签时,请确保设置
self.directionsLabel

messageTutorial
方法中创建
directionsLabel
时,您似乎没有将
self.directionsLabel
设置为任何内容。它是标签的本地实例。你应该在方法中的某个地方设置它


然后,在
视图中将其从superview中删除将起作用(测试以验证)。

与其将标签设置为零并有效销毁标签对象(假设启用了自动引用计数),不如在需要时使用以下方法隐藏和显示标签

[self.directionsLabel setHidden:YES]; // hides it
[self.directionsLabel setHidden:NO]; // shows it

你已经有了正确的想法,将你不使用的对象设置为零,并将它们从超级视图中删除,但这样做太过分了。UILabel对象使用的内存量可以忽略不计,最好只创建一次对象,然后根据需要更改其属性。

我想OP只是说他们尝试了这两种方法,但都没有成功。谢谢!问题是“这两个东西”不是独立的,它们实际上是可以工作的,你只需要交换这两条指令的顺序;完成块中的removeFromSuperview似乎可以很好地移除标签。