iOS以编程方式创建视图

时间:2013-06-04 20:06:53

标签: ios uiview sleep

我正在尝试以编程方式从我的.m文件之一创建一个新的UIView,然后在5秒后返回到我现有的视图。似乎我的逻辑是关闭的,因为这不是我想做的事情。我的代码如下。

UIView *mainView = self.view;

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

sleep(5);
self.view = mainView;

它似乎只是睡了5秒然后什么都没做。

我想做以下事情,

  • 存储起始视图
  • 创建新视图
  • 显示灰色视图
  • 等待5秒
  • 显示原始视图

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

感谢您的帮助! :)

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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];
}

非常初步,但应该有效

答案 2 :(得分: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];
});