Display Alert Message from viewDidLoad

后端 未结 4 1369
孤街浪徒
孤街浪徒 2021-01-08 01:01

I want to display a alert message from viewDidLoad() method of ViewController.m instead from viewDidAppear() method.

Here is m

4条回答
  •  心在旅途
    2021-01-08 01:10

    Swift 3 iOS 10, I used operation queue to put the block of code that updates the UI onto the main thread.

    import UIKit
    
    class ViewController2: UIViewController {
    
    var opQueue = OperationQueue()
    
    override func viewDidLoad() {
        super.viewDidLoad()
            let alert = UIAlertController(title: "MESSAGE", message: "HELLO WORLD!", preferredStyle: UIAlertControllerStyle.alert)
            // add an action (button, we can add more than 1 buttons)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            // show the alert
            self.opQueue.addOperation {
                // Put queue to the main thread which will update the UI
                OperationQueue.main.addOperation({
                    self.present(alert, animated: true, completion: nil)
                })
            }
        }
    }
    

    In short we are using async. This allows the alert message to be displayed as expected (even when we are in viewDidLoad()).

提交回复
热议问题