Jak utworzyć UIAlertView w języku Swift?

Pracowałem nad stworzeniem UIAlertView w języku Swift, ale z jakiegoś powodu nie mogę poprawnie odczytać instrukcji, ponieważ dostaję ten błąd:

Nie można znaleźć przeciążenia dla 'init', który akceptuje dostarczone argumenty

Oto Jak to napisałem:

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

Więc żeby to nazwać używam:

button2Alert.show()

W tej chwili jest upaść i po prostu nie wydaje się, aby uzyskać składni prawo.

Author: Dmitry, 2014-06-03

30 answers

Z klasy UIAlertView:

// UIAlertView jest przestarzały. Użyj UIAlertController z preferredStyle of UIAlertControllerStyleAlert instead

Na iOS 8 możesz to zrobić:
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)

Teraz UIAlertController jest pojedynczą klasą do tworzenia i interakcji z tym, co znaliśmy jako UIAlertView s I UIActionSheet s na iOS 8.

Edit: do obsługi akcji:

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

Edycja dla 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)

Edycja dla Swift 4:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.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)
 782
Author: Oscar Swanros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-13 00:34:36

One Button

Zrzut Ekranu Z Jednym Przyciskiem

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

Dwa Przyciski

Zrzut Ekranu Z Dwoma Przyciskami

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

Trzy Przyciski

Tutaj wpisz opis obrazka

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: UIAlertActio.nStyle.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)
    }
}

Obsługa Krany Przycisków

handler było nil w powyższych przykładach. Możesz zastąpić nil zamknięciem , aby zrobić coś, gdy użytkownik naciśnie przycisk. Na przykład:

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

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

}))

Uwagi

  • wiele przycisków niekoniecznie musi używać różnych typów UIAlertAction.Style. Wszystkie mogą być .default.
  • dla więcej niż trzech przycisków rozważ użycie arkusza akcji. Konfiguracja jest bardzo podobna. oto przykład.
 365
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-05 14:18:24

Możesz utworzyć UIAlert używając standardowego konstruktora, ale 'legacy' wydaje się nie działać:

let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
 111
Author: Ben Gottlieb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-29 13:47:38

Click of View

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

}

Gotowe za pomocą dwóch przycisków OK & Cancel

 17
Author: Hiren Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-10 16:21:34

Jeśli celujesz w iOS 7 i 8, potrzebujesz czegoś takiego, aby upewnić się, że używasz odpowiedniej metody dla każdej wersji, ponieważ UIAlertView jest przestarzały w iOS 8, Ale UIAlertController nie jest dostępny w 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()
    }
}
 12
Author: AstroCB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-13 21:14:01

Pokaż UIAlertView w języku swift:-

Protokół UIAlertViewDelegate

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

Pokaż UIAlertViewController w języku swift:-

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)
 11
Author: Anit Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-08 13:41:16

Po prostu nie podawaj w konstruktorze innych napisów przycisków.

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

alertView.show()

Ale Zgadzam się z Oscarem, ta klasa jest przestarzała w iOS 8, więc nie będzie żadnego użycia UIAlertView, jeśli robisz aplikację tylko na iOS 8. W przeciwnym razie powyższy kod zadziała.

 11
Author: Peymankh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-22 14:51:07

Z rozszerzeniami protokołu Swift 2, możesz utworzyć protokół, który zapewnia domyślną implementację kontrolerów widoku:

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!")
    }
}
 10
Author: knshn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-04 13:32:49

Znalazłem ten,

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

Niezbyt dobre, ale działa :)

Aktualizacja:

Ale znalazłem w pliku nagłówkowym jako:

extension UIAlertView {
    convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
Ktoś może może to wyjaśnić.
 9
Author: Mujah Maskey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-03 19:05:20

Dla SWIFT4 , myślę, rozszerzenie UIViewController i stworzenie kontroli potwierdzenia wielokrotnego użytku jest najbardziej eleganckim sposobem.

Możesz rozszerzyć UIViewController Jak poniżej:

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

Wtedy możesz go użyć w każdej chwili:

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

        } else { //User has clicked on Cancel

        }
    }
 6
Author: emreoktem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-04 01:23:02
    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")
                }
            }
        }
    }
 5
Author: Jayesh Miruliya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-10 12:35:47

Mam jeszcze jedną sztuczkę. Załóżmy, że masz 5 klas, w których należy zastosować alert wylogowania. Spróbuj z rozszerzeniem klasy swift.

File-New-Swift class-Name it.

Dodać:

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

Zaimplementuj używając: self.makeLogOutAlert (). Mam nadzieję, że to pomoże.

 5
Author: A.G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-08 14:50:55

Zrobiłem klasę singleton, aby było to wygodne w użyciu z dowolnego miejsca w aplikacji: https://github.com/Swinny1989/Swift-Popups

Możesz następnie utworzyć wyskakujące okienko z wieloma przyciskami, takimi jak:

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

Lub wyskakujące okienka z jednym przyciskiem, takie jak:

Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
 5
Author: Swinny89,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-26 09:31:58

Swift 3

Poniżej znajduje się prosty przykład, jak utworzyć prosty alert za pomocą jednego przycisku za pomocą Swift 3.

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

W powyższym przykładzie funkcja callback dla operacji została pominięta, ponieważ domyślne zachowanie widoku alertu z jednym przyciskiem ma znikać po kliknięciu przycisku.

Oto jak utworzyć kolejną akcję, którą można dodać do alertu za pomocą "alert.addAction(akcja)". Różne style są .default, .destrukcyjne i .odwołaj.

let action = UIAlertAction(title: "Ok", style: .default) { action in
    // Handle when button is clicked    
}
 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 07:25:26

W Swift 4.1 i Xcode 9.4.1

SIMPLE ALERT

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

ALERT WITH SHARED CLASS

Jeśli chcesz współdzielony styl klasy (napisz raz Użyj co gdzie)

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() {
    }
}

Teraz wywołaj alert tak w każdym ware

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

PRESENT ALERT TOP WSZYSTKIE OKNA

Jeśli chcesz wyświetlić alert na wierzchu wszystkich widoków, użyj tego kodu

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

Wywołanie funkcji

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

ALERT WITH TEXTFIELDS

Jeśli chcesz Dodaj pola tekstowe do alertu.

//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)

}
 5
Author: iOS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-12 06:18:29

Otrzymałem następujący UIAlertView kod inicjalizacyjny do kompilacji bez błędów (i thing The last, varyadic part is tricky maybe). Ale musiałem się upewnić, że klasa self (którą przechodzę jako delegat) przyjmuje protokół UIAlertViewDelegate, aby błędy kompilacji zniknęły:

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

Przy okazji, to jest błąd, który otrzymałem (od Xcode 6.4):

Nie można znaleźć inicjalizatora dla typu 'UIAlertView', który akceptuje lista argumentów typu " (title: String, message: String, delegate: MyViewController, cancelButtonTitle: String, otherButtonTitles: String) "

Jak inni wspominali, powinieneś przenieść do UIAlertController, jeśli możesz kierować iOS 8.x+. Aby obsługiwać system iOS 7, użyj powyższego kodu (system iOS 6 nie jest obsługiwany przez Swift).

 4
Author: Nicolas Miari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-14 07:44:33

Powód, dla którego nie działa, ponieważ pewna wartość przekazana do funkcji jest nieprawidłowa. swift nie lubi Objective-C, można dodawać nil do argumentów, które są typem klasy bez żadnych Ograniczeń (może być). Argument otherButtonTitles jest zdefiniowany jako nieobowiązkowy, którego Typ nie ma (?) na jego końcu. więc musisz przekazać mu konkretną wartość.

 3
Author: Oscar Wu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-29 16:33:23
@IBAction func Alert(sender: UIButton) {

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

    alertView.show()

}

Spróbuj tego

 3
Author: gskril,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-13 22:55:22

Użyj tego kodu, aby wyświetlić 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)

Reference: Swift Show Alert using UIAlertController

 3
Author: Shaba Aafreen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-10 02:47:51

In 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)
 3
Author: luhuiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-05 06:34:27
 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)

}
 3
Author: Mr.Javed Multani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 09:28:21

SWIFT 4: po prostu utwórz rozszerzenie do UIViewController w następujący sposób:

   extension  UIViewController{

   func showSucsessAlert(withTitle title: String, andMessage 
    message:String){
        let alert = UIAlertController(title: title, message: message, 
         preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: 
        UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
         }
    }

Teraz w Twoim viewcontrollerze, bezpośrednio wywołaj powyższą funkcję tak, jakby była dostarczana przez UIViewController.

    yourViewController.showSucsessAlert(withTitle: 
      "YourTitle", andMessage: "YourCustomTitle")
 2
Author: Shikha Budhiraja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-03 14:10:05

Spróbuj Tego. Umieść Poniższy Kod W Przycisku.

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)
 2
Author: Sagar Sangani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-02 13:28:45

Oto zabawny przykład w języku 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)
  }
}
 1
Author: Zorayr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-25 06:51:27

Oto dość prosta funkcja AlertView w języku 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()

    }

musisz przekazać wiadomość jako ciąg znaków, w którym używasz tej funkcji.

 1
Author: iAnkit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-15 09:04:29

The Old Way: 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 {

    // ...
   }
  }

Nowy Sposób: 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) {
 // ...
}
 1
Author: Shanmugasundharam selvadurai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-04 08:43:26

Na IOS 9 możesz to zrobić

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)
 1
Author: Keshav Gera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-28 10:46:07

/ / Klasa Generyczna Dla 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)
        }
    }
}
}

Użycie: -

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
 1
Author: Pratyush Pratik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 13:24:52
  // 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()
 1
Author: Hitesh Chauhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-04 08:35:47

Poniżej znajduje się kod wielokrotnego użytku dla widoku alertu i arkusza akcji, wystarczy napisać jedną linię, aby wyświetlić alert w dowolnym miejscu w aplikacji

class AlertView{

    static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

        for button in buttons{

            var style = UIAlertActionStyle.default
            let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
            if buttonText == "cancel"{
                style = .cancel
            }
            let action = UIAlertAction(title: button, style: style) { (_) in
                completionHandler(button)
            }
            alert.addAction(action)
        }

        DispatchQueue.main.async {
            if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
                rootViewController.present(alert, animated: true, completion: nil)
            }

        }
    }
}

Użycie:

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
            print(button)
        }
    }

}
 1
Author: indrajit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-15 11:01:09