首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >popViewControllerAnimated:YES不工作

popViewControllerAnimated:YES不工作
EN

Stack Overflow用户
提问于 2014-11-14 05:16:46
回答 3查看 868关注 0票数 1

我正在写一个单元测试,我发现popViewControllerAnimated:YES不起作用。

代码语言:javascript
复制
(void)testNavi {
  UINavigationController *navi = [[UINavigationController alloc] init];
  UIViewController *controllerA = [[UIViewController alloc] initWithNibName:nil bundle:nil];
  UIViewController *controllerB = [[UIViewController alloc] initWithNibName:nil bundle:nil];
  [navi pushViewController:controllerA animated:NO];
  [navi pushViewController:controllerB animated:NO];
  [navi popViewControllerAnimated:YES];
  XCTAssertEqual(navi.topViewController, controllerA);
}

如果我将navi popViewControllerAnimated:YES更改为navi popViewControllerAnimated:NO,则可以正常工作。我也不知道原因。

EN

回答 3

Stack Overflow用户

发布于 2014-11-14 06:49:44

最好在创建视图后再调用popViewControllerAnimated。因此您可以创建NavigationController的子类,并像这样实现它。

代码语言:javascript
复制
- (void)init {
   self = [super init];
   if (self) {
      UIViewController *controllerA = [[UIViewController alloc] initWithNibName:nil bundle:nil];
      UIViewController *controllerB = [[UIViewController alloc] initWithNibName:nil bundle:nil];
      self.viewControllers = @[controllerA, controllerB];
   }
   return self;
}

- (void)viewWillAppear {
   [self popViewControllerAnimated:YES];
}
票数 0
EN

Stack Overflow用户

发布于 2014-11-29 14:20:54

这是因为动画在另一个线程上异步发生。弹出视图控制器的动画只需要很少的时间,但测试断言是在动画完成之前进行的,因此topViewController尚未更改。

对此进行测试的最佳方法是模拟UINavigationController并验证是否调用了popViewController:YES

票数 0
EN

Stack Overflow用户

发布于 2016-08-26 12:57:42

当推送是动画时,我在测试pushViewController时也遇到了类似的问题。

我能够通过将断言包装在这个来自matt的方便的delay函数中来解决这个问题。

在测试中引入延迟时,有必要使用ensure来确保检查断言。否则,测试在延迟代码执行之前完成,导致通过的测试不会检查您的断言!

代码语言:javascript
复制
// code to push the view controller goes here...

// set up the expectation
let expectation = expectationWithDescription("anything you want")

// now, assert something about the navigation controller 
// after waiting 1/10th second for the animation to finish
delay (0.1) {

    // for example: Navigation controller should have the 
    // expected number of view controllers
    XCTAssertEqual(1, navigationController.viewControllers.count)

    // if we get this far, then assertions passed and we must
    // fulfill expectations to pass the test
    expectation.fulfill()
}

// wait longer than the delay value, so the code in the delay closure
// has time to finish
waitForExpectationsWithTimeout(0.2, handler: nil)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26918564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档