在viewDidLoad和viewWillAppear之间的Swift长延迟

时间:2015-06-23 16:53:08

标签: ios swift uitableview uiviewcontroller uimodalpresentationstyle

我遇到了一个问题,即在尝试呈现ViewController时我遇到了很长的延迟。我想在用户点击需要高级访问权限的UITableViewCell时显示升级提醒。在提交的ViewController中,我输入了调试代码:

override func viewDidLoad() {
    super.viewDidLoad()

    println("\(NSDate()) viewDidLoad")
    // Set Navigation Title font and color
    self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "UbuntuCondensed-Regular", size: 22)!,
        NSForegroundColorAttributeName: UIColor.whiteColor()]
    println("\(NSDate()) end of viewDidLoad")
}

override func viewWillAppear(animated: Bool) {
    println("\(NSDate()) before super.viewWillAppear(animated)")
    super.viewWillAppear(animated)
    println("\(NSDate()) after super.viewWillAppear(animated)")
}

override func viewDidAppear(animated: Bool) {
    println("\(NSDate()) before super.viewDidAppear(animated)")
    super.viewDidAppear(animated)

    println("\(NSDate()) after super.viewDidAppear(animated)")
}

println语句导致:

2015-06-23 16:36:54 +0000 viewDidLoad
2015-06-23 16:36:54 +0000 end of viewDidLoad
2015-06-23 16:36:57 +0000 before super.viewWillAppear(animated)
2015-06-23 16:36:57 +0000 after super.viewWillAppear(animated)
2015-06-23 16:36:58 +0000 before super.viewDidAppear(animated)
2015-06-23 16:36:58 +0000 after super.viewDidAppear(animated)

正如您所看到的,viewDidLoad的结尾与viewWillAppear的开头之间有3秒的延迟。我无法弄清楚为什么会这样。我在ViewController内以编程方式创建视图,因此这里没有使用故事板。

这是我必须提供ViewController的代码:

// Create the upgrade view contorller
let upgradeVC = UpgradeViewController()
// Set the presentation context
self.providesPresentationContextTransitionStyle = true
self.definesPresentationContext = true
// Set the upgrade controller to be modal over current context
upgradeVC.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
// Show the view controller
self.navigationController?.presentViewController(upgradeVC, animated: true, completion: nil)

2 个答案:

答案 0 :(得分:4)

创建和呈现视图控制器应该在主线程上完成。

(当视图更新被延迟时,它几乎总是意味着您错误地在后台线程上工作。)

答案 1 :(得分:0)

我将其放置在此处,以便人们理解list = [] list[0].append(0) viewDidLoad的延迟对于您在viewDidAppear UITableViewController中来说是没有错的。

在Swifts didSelectRowAt async回调中显然存在一个隐藏的await UITableViewController后台线程错误:

如果您的代码看起来像这样,则可能介于didSelectRowAtviewDidLoad之间2或3秒

viewDidAppear

(尽管您无可奉告)

这就是您在Swift 4中加快速度的方法

class ViewControllerList: UITableViewController{
   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)       
   {
        let storyBoard = UIStoryboard(name: "Display", bundle:nil)
        let displayView = storyBoard.instantiateViewController(withIdentifier: "ViewControllerDisplay") as! ViewControllerDisplay
        self.present(displayView, animated: true, completion: nil)
   }
}