How to show a message on screen for a few seconds?

This shows an Alert View on screen and auto closes after 1 second. You can set the time.

 var alert:UIAlertController!
    func showAlert() {
        self.alert = UIAlertController(title: "Alert", message: "Wait Please!", preferredStyle: UIAlertControllerStyle.Alert)
        self.presentViewController(self.alert, animated: true, completion: nil)
        NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
    }

    func dismissAlert(){
        // Dismiss the alert from here
        self.alert.dismissViewControllerAnimated(true, completion: nil)
    }

I was able to accomplish what I wanted after researching what was suggested in the comment by @mn1. I used animateWithDuration to fade the label away. Here is some example code:

myLabel.hidden = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
    self.myLabel.alpha = 0
})

This code became shorter with iOS 10. Thanks to @fatihyildizhan

func showAlert() {
    let alert = UIAlertController(title: "Alert", message: "Wait Please!", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false, block: { _ in alert.dismiss(animated: true, completion: nil)} )
}

Swift 3 Solution:

  // Define a view
  var popup:UIView!
  func showAlert() {
    // customise your view
    popup = UIView(frame: CGRect(x: 100, y: 200, width: 200, height: 200))
    popup.backgroundColor = UIColor.redColor

    // show on screen
    self.view.addSubview(popup)

    // set the timer
    Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.dismissAlert), userInfo: nil, repeats: false)
  }

  func dismissAlert(){
    if popup != nil { // Dismiss the view from here
      popup.removeFromSuperview()
    }
  }

Swift 2 Solution:

  // Define a view
  var popup:UIView!
  func showAlert() {
    // customise your view
    popup = UIView(frame: CGRect(x: 100, y: 200, width: 200, height: 200))
    popup.backgroundColor = UIColor.redColor()

    // show on screen
    self.view.addSubview(popup)

    // set the timer
    NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
  }

  func dismissAlert(){
    // Dismiss the view from here
    popup.removeFromSuperview()
  }

  // Don't forget to call showAlert() function in somewhere

Tags:

Ios

Swift