2013-06-04 177 views
0

我试图以编程方式从我的.m文件之一创建新的UIView,然后在5秒后返回到我现有的视图。看起来我的逻辑是关闭的,因为这不是我想要的。我的代码如下。iOS以编程方式创建视图

UIView *mainView = self.view; 

UIView *newView = [[UIView alloc] init]; 
newView.backgroundColor = [UIColor grayColor]; 
self.view = newView; 

sleep(5); 
self.view = mainView; 

它似乎只是睡5秒,然后什么都不做。

我要做到以下几点,

  • 商店开始视图
  • 创建新的视图
  • 显示灰色视图
  • 等待5秒钟
  • 显示我原来的观点

我哪里错了?我觉得它必须是我的逻辑,或者我错过了这些步骤的关键部分。

感谢您的帮助! :)

+2

使用'performSelector:withObject:afterDelay:'不要使用sleep()。将'sleep'部分之后的所有逻辑分组到一个方法中并使用'performSelector'。 – danypata

+0

@danypata我应该使用命令,'[self performSelector:@selector(returnToMainView)withObject:mainView afterDelay:5.0]; '然后创建一个方法' - (void)returnToView:(UIView *)mainView {' –

+0

是的,这应该工作。 – danypata

回答

1

首先,不要使用sleep()。您应该使用performSelector:withObject:afterDelay:方法。类似这样的:

-(void)yourMethodWhereYouAreDoingTheInit { 
    UIView *mainView = self.view; 
    UIView *newView = [[UIView alloc] init]; 
    newView.backgroundColor = [UIColor grayColor]; 
    self.view = newView; 
    [self performSelector:@selector(returnToMainView:) 
       withObject:mainView 
       afterDelay:5.0]; 
} 

-(void)returnToMainView:(UIView *)view { 
    //do whatever after 5 seconds 
} 
0
- (void)showBanner { 
UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds]; 
newView.backgroundColor = [UIColor grayColor]; 
[self.view addSubview:newView]; 

[newView performSelector:@selector(removeFromSuperView) withObject:nil afterDelay:5.0f]; 
} 

非常初步的,但应该工作

+0

'没有可见的@interface为UIView声明选择器addSubView' –

+0

'addSubview',而不是'addSubView'。 – rmaddy

+0

对不起,我从Windows PC写的,没有检查。我认为主题作者能够理解我想说的话。 – NeverBe

0

使用GCD将产生更多可读代码,但最终它是一个优先选择。

// Create grayView as big as the view and add it as a subview 
UIView *grayView = [[UIView alloc] initWithFrame:self.view.bounds]; 
// Ensure that grayView always occludes self.view even if its bounds change 
grayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
grayView.backgroundColor = [UIColor grayColor]; 
[self.view addSubview:grayView]; 
// After 5s remove grayView 
double delayInSeconds = 5.0; 
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); 
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
    [grayView removeFromSuperview]; 
});