Shahzaib Qureshi
Shahzaib Qureshi

Reputation: 920

Show an UIAlertController from a button on an UITableViewCell

This is what I coded inside a button in a UITableViewCell.

var shareAlert = UIAlertController(title: "Post Alert", 
    message: "Your Post has been Shared with your Friends", 
    preferredStyle: UIAlertControllerStyle.Alert)

var Ok = UIAlertAction(title: "Ok", 
    style: UIAlertActionStyle.Default, 
    handler: nil)

shareAlert.addAction(Ok)
shareAlert.presentViewController(shareAlert, animated: true, completion: nil)

When the user clicks the button I want it to show this alert, but the app crashes as soon as I click the button. Am I doing it wrong? How do I show an alert view from a button in a UITableViewCell?

Upvotes: 2

Views: 2351

Answers (3)

Gintama
Gintama

Reputation: 1152

It crashed because of this line

shareAlert.presentViewController(shareAlert, animated: true, completion: nil)

A controller cannot present itself, so

Replace

shareAlert.presentViewController(shareAlert, ...) 

by

yourCurrentViewController.presentViewController(shareAlert, ...)

And you should not use UIAlertView because it was deprecated in iOS 9 and maybe obsoleted in the next iOS, so use UIAlertController and you don't have to change it in near future

Upvotes: 6

Dejan Skledar
Dejan Skledar

Reputation: 11435

Instead of using UIAlertController you can use UIAlertView, like this:

 var alert = UIAlertView(title: "Post Alert", message: "Your Post has been Shared with your Friends", delegate: nil, cancelButtonTitle: "Ok")
 alert.show()

Documentation: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAlertView_Class/index.html

Note:

UIAlertView is deprecated in iOS 9.

Upvotes: -1

Mousavian
Mousavian

Reputation: 1475

Please check this: https://stackoverflow.com/a/32574681/5304286

You can call alertShow function in this file to show simple message by the way:

 Utility.UI.alertShow("message", withTitle: "title", viewController: self)

Upvotes: 0

Related Questions