How to make alert view appear in center of the view controller using swift 2.2

3k views Asked by At

I am developing a app using swift 2.2, in my app I am having a button when a user taps on that button alert view will appear which contains four buttons in vertical everything works fine but alert view appearing in bottom of the view controller how to display in center of the view controller.

Note:I don't want to display any title and message just i have to show four buttons only.

If I use this one:

let alert = UIAlertController(title: " ", message: "select colors", preferredStyle: UIAlertControllerStyle.Alert)

It helps to display in center of the view controller but without title and message it looks not better so I used following code

Code:

let alert = UIAlertController()

alert.addAction(UIAlertAction(title: "Red Color", style: UIAlertActionStyle.Default, handler: nil))

alert.addAction(UIAlertAction(title: "Blue Color", style: UIAlertActionStyle.Default, handler: nil))

alert.addAction(UIAlertAction(title: "Green Color", style: UIAlertActionStyle.Default, handler: nil))

alert.addAction(UIAlertAction(title: "Yellow Color", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)
4

There are 4 answers

0
gasho On BEST ANSWER

Just set the title and the message to nil. I tested it in swift 3.

let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.alert)
2
Hiroki Murahi On

you can do this:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
2
KhanShaheb On

It will come automatically in center for its Property :) but what you actually wanted?

1
Ketan Parmar On

Add below lines in your code before you present your alert,

alert.popoverPresentationController!.sourceView = self.view
alert.popoverPresentationController!.sourceRect = self.view.bounds