How to add Progress bar to UIAlertController?

Nik picture Nik · Jul 28, 2015 · Viewed 16.2k times · Source

I want to add progress bar in swift iOS 8 UIAlertController. Is this possible? Is there any way to subclass UIAlertController and add progres bar and connect some delegate functions?

thanks

Answer

coyer picture coyer · Oct 29, 2015

If you just need a progressbar you can simply add it as a subview as follows:

Updated for Swift 5:

//  Just create your alert as usual:
let alertView = UIAlertController(title: "Please wait", message: "Need to download some files.", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

//  Show it to your users
present(alertView, animated: true, completion: {
    //  Add your progressbar after alert is shown (and measured)
    let margin:CGFloat = 8.0
    let rect = CGRect(x: margin, y: 72.0, width: alertView.view.frame.width - margin * 2.0 , height: 2.0)
    self.progressView = UIProgressView(frame: rect)
    self.progressView!.progress = 0.5
    self.progressView!.tintColor = self.view.tintColor
    alertView.view.addSubview(self.progressView!)
})

Swift 2.0:

//  Just create your alert as usual:
let alertView = UIAlertController(title: "Please wait", message: "Need to download some files.", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

//  Show it to your users
presentViewController(alertView, animated: true, completion: {
    //  Add your progressbar after alert is shown (and measured)
    let margin:CGFloat = 8.0
    let rect = CGRectMake(margin, 72.0, alertView.view.frame.width - margin * 2.0 , 2.0)
    let progressView = UIProgressView(frame: rect)
    progressView.progress = 0.5
    progressView.tintColor = UIColor.blueColor()
    alertView.view.addSubview(progressView)
})

It's quite difficult to resize the UIAlertController for bigger content but for a progressbar this should do the trick.