0

我正在尝试从我的一个.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 秒
  • 显示我的原始视图

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

谢谢你的帮助!:)

4

3 回答 3

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
}
于 2013-06-04T20:28:34.257 回答
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];
}

非常初步,但应该可以

于 2013-06-04T20:15:19.160 回答
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];
});
于 2013-06-04T20:35:14.353 回答