对于我的应用程序的教程,我试图创建一个UILabel,当视图出现时该UILabel会在显示的屏幕上漂移,然后销毁该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,并在视图出现/重新出现时添加/创建一个新的UILabel?
谢谢。
最佳答案
viewWillDisappear
方法中的代码是向后的。你需要:
- (void)viewWillDisappear:(BOOL)animated {
NSLog(@"view is disappearing");
[self.directionsLabel removeFromSuperview];
self.directionsLabel = nil;
}
如您所愿,在尝试将其删除之前将
self.directionsLabel
设置为nil
会导致无操作。另外,在创建标签时,请务必设置
self.directionsLabel
。