Подтвердить что ты не робот

Как создать UIAlertView в Swift?

Я работал над созданием UIAlertView в Swift, но по какой-то причине я не могу правильно понять утверждение, потому что я получаю эту ошибку:

Не удалось найти перегрузку для 'init', который принимает предоставленные аргументы

Вот как я это написал:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)

Затем для вызова я использую:

button2Alert.show()

На данный момент это сбой, и я просто не могу понять синтаксис правильно.

4b9b3361

Ответ 1

Из класса UIAlertView:

//UIAlertView устарела. Вместо этого используйте UIAlertController с предпочитаемым стилем UIAlertControllerStyleAlert

На iOS 8 вы можете сделать это:

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)

Теперь UIAlertController - это единый класс для создания и взаимодействия с тем, что мы знали как UIAlertView и UIActionSheet в iOS 8.

Изменить: для обработки действий:

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")
    }
}}))

Редактировать для 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)

Редактировать для 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)

Ответ 2

Одна кнопка

One Button Screenshot

class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
}

Две кнопки

Two Button Alert Screenshot

class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)

        // add the actions (buttons)
        alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
}

Три кнопки

enter image description here

class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)

        // add the actions (buttons)
        alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
}

Обработка нажатий кнопок

handler был nil в приведенных выше примерах. Вы можете заменить nil на замыкание, чтобы что-то делать, когда пользователь нажимает кнопку. Например:

alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in

    // do something like...
    self.launchMissile()

}))

Notes

  • Несколько кнопок не обязательно должны использовать разные типы UIAlertAction.Style. Они все могут быть .default.
  • Для более чем трех кнопок рассмотрите возможность использования листа действий. Настройка очень похожа. Вот пример.

Ответ 3

Вы можете создать UIAlert с помощью стандартного конструктора, но "устаревшее", похоже, не работает:

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here a message"
alert.addButtonWithTitle("Understood")
alert.show()

Ответ 4

В Swift 4.2 и Xcode 10

Способ 1:

ПРОСТОЕ ПРЕДУПРЕЖДЕНИЕ

let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)

     let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
     })
     alert.addAction(ok)
     let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
     })
     alert.addAction(cancel)
     DispatchQueue.main.async(execute: {
        self.present(alert, animated: true)
})

Способ 2:

ALERT с общим классом

Если вы хотите стиль общего класса (пишите один раз, используйте каждый раз)

import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()

    //Show alert
    func alert(view: UIViewController, title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert.addAction(defaultAction)
        DispatchQueue.main.async(execute: {
            view.present(alert, animated: true)
        })
    }

    private override init() {
    }
}

Теперь вызывайте оповещения вот так в каждой посуде

SharedClass.SharedInstance.alert(view: self, title: "Your title here", message: "Your message here")

Способ 3:

НАСТОЯЩИЙ АЛЕРТ ВЕРХ ВСЕХ ОКОН

Если вы хотите создать оповещение поверх всех просмотров, используйте этот код

func alertWindow(title: String, message: String) {
    DispatchQueue.main.async(execute: {
        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
        alertWindow.windowLevel = UIWindowLevelAlert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert2.addAction(defaultAction2)

        alertWindow.makeKeyAndVisible()

        alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
    })
}

Вызов функции

SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")

Способ 4:

Оповещение с расширением

extension  UIViewController {

    func showAlert(withTitle title: String, withMessage message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
        })
        alert.addAction(ok)
        alert.addAction(cancel)
        DispatchQueue.main.async(execute: {
            self.present(alert, animated: true)
        })
    }
}

Теперь звоните вот так

//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
    showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}

Способ 5:

ALERT с текстовыми полями

Если вы хотите добавить текстовые поля для оповещения.

//Global variables
var name:String?
var login:String?

//Call this function like this:  alertWithTF() 
//Add textfields to alert 
func alertWithTF() {

    let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
    // Login button
    let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
        // Get TextFields text
        let usernameTxt = alert.textFields![0]
        let passwordTxt = alert.textFields![1]
        //Asign textfileds text to our global varibles
        self.name = usernameTxt.text
        self.login = passwordTxt.text

        print("USERNAME: \(self.name!)\nPASSWORD: \(self.login!)")
    })

    // Cancel button
    let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })

    //1 textField for username
    alert.addTextField { (textField: UITextField) in
        textField.placeholder = "Enter username"
        //If required mention keyboard type, delegates, text sixe and font etc...
        //EX:
        textField.keyboardType = .default
    }

    //2nd textField for password
    alert.addTextField { (textField: UITextField) in
        textField.placeholder = "Enter password"
        textField.isSecureTextEntry = true
    }

    // Add actions
    alert.addAction(loginAction)
    alert.addAction(cancel)
    self.present(alert, animated: true, completion: nil)

}

Способ 6:

Оповещение в SharedClass с расширением

//This is your shared class
import UIKit

 class SharedClass: NSObject {

 static let sharedInstance = SharedClass()

 //Here write your code....

 private override init() {
 }
}

//Alert function in shared class
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

Теперь звоните прямо так

self.showAlert(title: "Your title here...", msg: "Your message here...")

Способ 7:

Оповещение без общего класса с расширением в отдельном классе для оповещения.

Создайте один новый класс Swift и import UIKit. Скопируйте и вставьте код ниже.

//This is your Swift new class file
import UIKit
import Foundation

extension UIAlertController {
    class func alert(title:String, msg:String, target: UIViewController) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) {
        (result: UIAlertAction) -> Void in
        })
        target.present(alert, animated: true, completion: nil)
    }
}

Теперь вызывайте функцию оповещения таким образом во всех ваших классах (одна строка).

UIAlertController.alert(title:"Title", msg:"Message", target: self)

Как это....

Ответ 5

Нажмите Просмотр

@IBAction func testClick(sender: UIButton) {

  var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
  self.presentViewController(uiAlert, animated: true, completion: nil)

  uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
   println("Click of default button")
  }))

  uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
   println("Click of cancel button")
  }))

}

Готово с двумя кнопками OK и Отмена

Ответ 6

Если вы ориентируетесь на iOS 7 и 8, вам нужно что-то подобное, чтобы убедиться, что вы используете правильный метод для каждой версии, потому что UIAlertView устарел в iOS 8, но UIAlertController недоступен в iOS 7:

func alert(title: String, message: String) {
    if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
        let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(myAlert, animated: true, completion: nil)
    } else { // iOS 7
        let alert: UIAlertView = UIAlertView()
        alert.delegate = self

        alert.title = title
        alert.message = message
        alert.addButtonWithTitle("OK")

        alert.show()
    }
}

Ответ 7

С расширением протокола Swift 2 вы можете сделать протокол, который предоставляет реализацию по умолчанию вашим контроллерам просмотров:

ShowsAlert.swift

import UIKit

protocol ShowsAlert {}

extension ShowsAlert where Self: UIViewController {
    func showAlert(title: String = "Error", message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }
}

ViewController.swift

class ViewController: UIViewController, ShowsAlert {
    override func viewDidLoad() {
        super.viewDidLoad()
        showAlert(message: "Hey there, I am an error message!")
    }
}

Ответ 8

Показать UIAlertView в быстром языке: -

Протокол UIAlertViewDelegate

let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()

Показать UIAlertViewController в быстром языке: -

let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

Ответ 9

Просто не предоставляйте otherButtonTitles в конструкторе.

let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")

alertView.show()

Но я согласен с Oscar, этот класс устарел в iOS 8, поэтому не будет никакого использования UIAlertView, если вы используете приложение только для iOS 8. В противном случае код будет работать.

Ответ 10

Я нашел этот,

var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();

Нехорошо, но он работает:)

Update:

но я нашел в файле заголовка как:

extension UIAlertView {
    convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}

кто-то может это объяснить.

Ответ 11

Для SWIFT4, я думаю, расширение UIViewController и создание элемента управления многоразового подтверждения является наиболее элегантным способом.

Вы можете расширить UIViewController как UIViewController ниже:

extension UIViewController {

func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    self.present(alert, animated: true, completion: nil)

    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
        completion(true)
    }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
        completion(false)
    }))
  }
}

Тогда вы можете использовать его в любое время:

 AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
        if result { //User has clicked on Ok

        } else { //User has clicked on Cancel

        }
    }

Ответ 12

    class Preview: UIViewController , UIAlertViewDelegate
    {
        @IBAction func MoreBtnClicked(sender: AnyObject)
        {
            var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
            moreAlert.show()
            moreAlert.tag=111;
        }

        func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
        {
            if alertView.tag==111
            {
                if buttonIndex==0
                {
                    println("No Thanks!")
                }
                else if buttonIndex==1
                {
                    println("Save Image")
                }
                else if buttonIndex == 2
                {
                    println("Email")
                }
                else if buttonIndex == 3
                {
                    println("Facebook")
                }
                else if buttonIndex == 4
                {
                    println("Whatsapp")
                }
            }
        }
    }

Ответ 13

У меня есть еще один трюк. Предположим, у вас есть 5 классов, в которых будет применяться предупреждение о выходе из системы. Попробуйте с быстрым расширением класса.

Файл - новый - класс Swift - назовите его.

Добавьте следующее:

public extension UIViewController
{

    func makeLogOutAlert()
    {
        var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

        refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
            self.navigationController?.popToRootViewControllerAnimated(true)
        }))

        refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
            refreshAlert .dismissViewControllerAnimated(true, completion: nil)
        }))

        presentViewController(refreshAlert, animated: true, completion: nil)
    }
}

Внедрить с помощью: self.makeLogOutAlert(). Надеюсь, что это поможет.

Ответ 14

Я сделал одноэлементный класс, чтобы его было удобно использовать из любого места в вашем приложении: https://github.com/Swinny1989/Swift-Popups

Затем вы можете создать всплывающее окно с несколькими кнопками, например:

Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
    if buttonPressed == "button one" { 
      //Code here
    } else if buttonPressed == "button two" {
        // Code here
    }
}

или всплывающее окно с одной кнопкой, как это:

Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")

Ответ 15

Swift 3

Ниже приведен простой пример создания простого предупреждения с помощью одной кнопки с Swift 3.

let alert = UIAlertController(title: "Title",
                              message: "Message",
                              preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)

В приведенном выше примере обратный вызов дескриптора действия был опущен, так как по умолчанию поведение предупреждения с одной кнопкой исчезает при нажатии кнопки.

Вот как создать другое действие, которое можно добавить в alert с помощью alert.addAction(action) ". Различные стили -.default,.destructive и .cancel.

let action = UIAlertAction(title: "Ok", style: .default) { action in
    // Handle when button is clicked    
}

Ответ 16

Я получил следующий код инициализации UIAlertView для компиляции без ошибок (я считаю, что последняя, ​​вариабельная часть, возможно, сложна). Но я должен был убедиться, что класс self (который я передаю как делегат) принимал протокол UIAlertViewDelegate для ошибок компиляции:

let alertView = UIAlertView(
                  title: "My Title",
                  message: "My Message",
                  delegate: self,
                  cancelButtonTitle: "Cancel",
                  otherButtonTitles: "OK"
                )

Кстати, это ошибка, которую я получал (с Xcode 6.4):

Невозможно найти инициализатор для типа 'UIAlertView', который принимает список аргументов типа '(title: String, message: String, delegate: MyViewController, cancelButtonTitle: String, otherButtonTitles: String) '

Как уже упоминалось, вам нужно перейти на UIAlertController, если вы можете настроить таргетинг на iOS 8.x+. Для поддержки iOS 7 используйте код выше (iOS 6 не поддерживается Swift).

Ответ 17

 let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

Ответ 18

Причина, по которой это не работает, потому что некоторая ценность, которую вы передали функции, неверна. swift не нравится Objective-C, вы можете поместить nil в аргументы, которые являются типами классов без каких-либо ограничений (может быть). Аргумент otherButtonTitles определяется как необязательный, его тип не имеет (?) В конце. поэтому вы должны передать ему конкретное значение.

Ответ 19

@IBAction func Alert(sender: UIButton) {

    var alertView:UIAlertView = UIAlertView()
    alertView.title = "Alert!"
    alertView.message = "Message"
    alertView.delegate = self
    alertView.addButtonWithTitle("OK")

    alertView.show()

}

Попробуйте это

Ответ 20

Используйте этот код для отображения alertview

  let alertController = UIAlertController(title: "Hello  Coders", message: "your alert message", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
        alertController.addAction(defaultAction)

        presentViewController(alertController, animated: true, completion: nil)

Ссылка: Swift Show Alert с помощью UIAlertController

Ответ 21

в xcode 9

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

Ответ 22

SWIFT 4: Просто создайте расширение для UIViewController следующим образом:

extension  UIViewController {        
    func showSuccessAlert(withTitle title: String, andMessage message:String) {
        let alert = UIAlertController(title: title, message: message,
                                  preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "OK".localized, style:
        UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

Теперь в вашем ViewController напрямую вызовите вышеуказанную функцию, как если бы они были предоставлены UIViewController.

    yourViewController.showSuccessAlert(withTitle: 
      "YourTitle", andMessage: "YourCustomTitle")

Ответ 23

попробуй это. Поместите сильфон в кнопку.

let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)

Ответ 24

SWIFT 4.X

    let alert = UIAlertController(title: "user entered title", message: "user entered message", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        print("Okay'd")
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in
        print("cancelled")
    }))
    self.present(alert, animated: true, completion: nil)

Ответ 25

Вот забавный пример в Swift:

private func presentRandomJoke() {
  if let randomJoke: String = jokesController.randomJoke() {
    let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
    presentViewController(alertController, animated:true, completion:nil)
  }
}

Ответ 26

Вот довольно простая функция AlertView в Swift:

class func globalAlertYesNo(msg: String) {
        let alertView = UNAlertView(title: "Title", message: msg)

        alertView.messageAlignment = NSTextAlignment.Center
        alertView.buttonAlignment  = UNButtonAlignment.Horizontal

        alertView.addButton("Yes", action: {

            print("Yes action")

        })

        alertView.addButton("No", action: {

            print("No action")

        })

        alertView.show()

    }

Вам нужно передать сообщение как строку, в которой вы используете эту функцию.

Ответ 27

Старый путь: UIAlertView

let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()

// MARK: UIAlertViewDelegate

 func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
 switch buttonIndex {

    // ...
   }
  }

Новый способ: UIAlertController

let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
 }
 alertController.addAction(cancelAction)

 let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
 }
 alertController.addAction(OKAction)
 self.presentViewController(alertController, animated: true) {
 // ...
}

Ответ 28

на IOS 9 вы можете сделать это

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)

Ответ 29

//Общий класс для UIAlertView

//MARK:- MODULES
import Foundation
import UIKit

//MARK:- CLASS
class Alert  : NSObject{

static let shared = Alert()

var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?

/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
        alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
    }
}

/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
    let version:NSString = UIDevice.current.systemVersion as NSString;

    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)

        alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in

            if let cancelAction = cancelAction {
                cancelAction()
            }
        }))
        alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert!, animated:true, completion:nil);
    }
}

/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
        let when = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: when){
            self.alert?.dismiss(animated: true, completion: nil)
        }
    }
}
}

Использование: -

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action
                        }) // with ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action 
}, cancelAction: {
 //cancel action
}) //with cancel and ok action

Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer

Ответ 30

  // UIAlertView is deprecated. Use UIAlertController 
  // title = title of the alert view.
  // message = Alert message you want to show.
  // By tap on "OK" , Alert view will dismiss.

 UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()