2013-06-04 174 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]; 
});