How would I create a UIAlertView in Swift?
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, 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.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
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)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert, animated: true, completion: nil)
How to add an action to a UIAlertView button using Swift iOS
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
How would I create a UIAlertView in Swift?
From the UIAlertView
class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, 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.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController
is a single class for creating and interacting with what we knew as UIAlertView
s and UIActionSheet
s on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
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)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert, animated: true, completion: nil)
How to add UITableView in a UIAlertView in swift
I dont think you can do that with UIAlertView
, but you can make a small View and present it modally or something like UIPopoverPresentationController
Create a simple Alert in swift
Try with following code
let alert = UIAlertView()
alert.title = "Title"
alert.message = "My message"
alert.addButtonWithTitle("Ok")
alert.show()
But in iOS 8
UIAlertView
is deprecated. So use UIAlertController
with a preferredStyle
of UIAlertControllerStyleAlert
. it should be
var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Custom Alert (UIAlertView) with swift
Code tested in Swift 5 and Xcode 10
How to make your own custom Alert
I was wanting to do something similar. First of all, UIAlertView
is deprecated in favor of UIAlertController
. See this answer for the standard way to display an alert:
- How would I create a UIAlertView in Swift?
And both UIAlertView
and UIAlertController
do not really allow much customization. One option is to use some third party code. However, I discovered that it isn't that difficult to create your own Alert by displaying another view controller modaly.
The example here is just a proof-of-concept. You can design your alert any way you want.
Storyboard
You should have two View Controllers. Your second view controller will be your alert. Set the class name to AlertViewContoller
and the Storyboard ID to alert
. (Both of these are names that we defined ourselves in the code below, nothing special about them. You can add the code first if you want. It might actually be easier if you add the code first.)
Set the background color for the root view (in your Alert View Controller) to clear (or translucent black is nice for an alert). Add another UIView
and center it with constraints. Use that as your alert background and put whatever you want inside. For my example, I added a UIButton
.
Code
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "alert")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(myAlert, animated: true, completion: nil)
}
}
AlertViewController.swift
import UIKit
class AlertViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Don't forget to hook up the outlets.
You can add an onTouchUp
event listener to the background view to dismiss the popup when the user clicks outside of it.
That's it. You should be able to make any sort of alert that you can imagine now. No need for third party code.
Here is another custom alert I made. Still ugly, but it shows more things you can do.
Other options
Sometimes there is no need to reinvent the wheel, though. I'm impressed with the third party project SDCAlertView (MIT license). It is written in Swift but you can use it with Objective-C projects as well. It offers a wide range of customability.
Swift Custom UIAlertView
Something like the following should allow it. Note there quite a few improvements that could be made. For example you could use a generic for the object being deleted instead of AnyObject. You also don't necessarily need to pass it in if you pass the closure inline anyway so you could probably just remove it.
You could also make your buttons more reusable rather than hard-coding to cancel and remove but now we're getting off topic :)
class ConfirmViewController : UIViewController {
var onCancel : (() -> Void)?
var onConfirm : ((AnyObject?) -> Void)?
var objectToDelete : AnyObject?
func cancelButtonPressed() {
// defered to ensure it is performed no matter what code path is taken
defer {
dismissViewControllerAnimated(false, completion: nil)
}
let onCancel = self.onCancel
// deliberately set to nil just in case there is a self reference
self.onCancel = nil
guard let block = onCancel else { return }
block()
}
func confirmationButtonPresssed() {
// defered to ensure it is performed no matter what code path is taken
defer {
dismissViewControllerAnimated(false, completion: nil)
}
let onConfirm = self.onConfirm
// deliberately set to nil just in case there is a self reference
self.onConfirm = nil
guard let block = onConfirm else { return }
block(self.objectToDelete)
}
}
let confirm = ConfirmViewController()
confirm.objectToDelete = NSObject()
confirm.onCancel = {
// perform some action here
}
confirm.onConfirm = { objectToDelete in
// delete your object here
}
How to create UIAlertView with Image
After iOS8 UIAlertView
is deprecated so Apple recommends you to use UIAlertController
instead of UIAlertView
. And to accomplish what you asked you can look here
How to add a TextField to UIAlertView in Swift
You can access the textfield with:
let textField = alert.textFieldAtIndex(0)
Then to change the placeholder text:
textField.placeholder = "Foo!"
And the keyboard type:
textField.keyboardType = ...
Related Topics
Wkwebview Not Loading Webpage - Renders Blank Screen in Swift
Save Generated Gif to Camera Roll
How to Check For an Active Internet Connection on iOS or Macos
How to Get the Indexpath.Row When an Element Is Activated
Firebase Custom Event Parameters Not Visible in Console
Ios Simple Tcp Connection Example
How to Develop or Migrate Apps For Iphone 5 Screen Resolution
How to Add Constraints Programmatically Using Swift
How to Safely Delete Contents of Xcode Derived Data Folder
Difference Between 'Yyyy' and 'Yyyy' in Nsdateformatter
Ios Launching Settings -≫ Restrictions Url Scheme
Firebase Query - Find Item With Child That Contains String
How Would I Create a Uialertview in Swift
How to Tell If Uiviewcontroller'S View Is Visible
How Disable Copy, Cut, Select, Select All in Uitextview
Ios :How to Get Facebook Album Photo'S Picker