I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
in xcode 9
From the
UIAlertView
class:On iOS 8, you can do this:
Now
UIAlertController
is a single class for creating and interacting with what we knew asUIAlertView
s andUIActionSheet
s on iOS 8.Edit: To handle actions:
Edit for Swift 3:
Edit for Swift 4.x:
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
Show UIAlertViewController in swift language :-
One Button
Two Buttons
Three Buttons
Handling Button Taps
The
handler
wasnil
in the above examples. You can replacenil
with a closure to do something when the user taps a button. For example:Notes
UIAlertAction.Style
types. They could all be.default
.Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.