Как бы я создал UIAlertView в Swift?
Я работал над созданием UIAlertView в Swift, но по какой-то причине я не могу правильно понять утверждение, потому что я получаю эту ошибку:
Не удалось найти перегрузку для 'init', который принимает предоставленные аргументы
Вот как я это написал:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Затем для вызова я использую:
button2Alert.show()
На данный момент это сбой, и я просто не могу понять синтаксис правильно.
36 ответов
От 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)
Одна кнопка
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)
}
}
Две кнопки
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)
}
}
Три кнопки
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)
}
}
Обработка нажатий кнопок
handler
было nil
в приведенных выше примерах. Вы можете заменить nil
с закрытием, чтобы сделать что-то, когда пользователь нажимает кнопку. Например:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Заметки
- Несколько кнопок не обязательно должны использовать разные
UIAlertAction.Style
типы. Они все могут быть.default
, - Для более чем трех кнопок рассмотрите использование листа действий. Настройка очень похожа. Вот пример.
Вы можете создать UIAlert, используя стандартный конструктор, но "устаревший", похоже, не работает:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
В Swift 4.2 и Xcode 9.4.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)
})
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")
НАСТОЯЩЕЕ ПРЕДУПРЕЖДЕНИЕ ВСЕ В ОКНАХ
Если вы хотите представить предупреждение поверх всех просмотров, используйте этот код
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")
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)
}
Щелчок зрения
@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")
}))
}
Готово с двумя кнопками ОК и Отмена
Если вы ориентируетесь на 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()
}
}
С помощью расширений протокола 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!")
}
}
Показать 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)
AlertView Swift 5 и выше:-
let alert = UIAlertController(title: LocalizedStringConstant.alert, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Retry", style: .cancel, handler: { (_) in })) self.present(alert, animated: true, completion: nil)
Просто не предоставляйте другие ButtonTitles в конструкторе.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
Но я согласен с Оскаром, этот класс устарел в iOS 8, поэтому UIAlertView не будет использоваться, если вы работаете только с iOS 8. В противном случае приведенный выше код будет работать.
Для SWIFT4, я думаю, расширяется 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
}
}
Я нашел это,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
не очень хорошо, но это работает:)
Обновить:
но я нашел в заголовочном файле как:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
кто-то может объяснить это.
Для iOS 13 Xcode 11+ Swift 5.X
UIAlertController
теперь может предоставлять оповещения, а также листы действий
Оповещения
// First instantiate the UIAlertController
let alert = UIAlertController(title: "Title",
message: "Message ?",
preferredStyle: .alert)
// Add action buttons to it and attach handler functions if you want to
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Just Do It!", style: .destructive, handler: nil))
alert.addAction(UIAlertAction(title: "Maybe", style: .default, handler: nil))
// Show the alert by presenting it
self.present(alert, animated: true)
Обратите внимание, что для всех кнопок действий принципиально закрывать представление предупреждений при нажатии. Вstyle
Параметр предназначен только для определения цвета текста (и некоторого порядка по умолчанию, в котором должны появляться кнопки, из которых можно изменить)
Пример функции обработчика может быть
func handler(_ action: UIAlertAction) {
if action.title == 'Title' {
// do stuff
}
}
В качестве побочного примечания я бы сказал, что вместо того, чтобы создавать 3 разных обработчика, вы можете просто сделать 1 и вернуться к элементу, который его спровоцировал, как показано выше. Мы также можем проверить alert.style
но снова у нас может быть несколько .default
стилизованные действия, я бы не рекомендовал
Таблицы действий
Объяснение аналогично, потому что основное отличие здесь заключается в том, что предупреждение прерывает пользователя, тогда как лист действий скользит снизу в iPhone и появляется в виде всплывающего окна на iPad.
Назначение листов действий - помочь пользователям принять решение о своих действиях в зависимости от их текущего состояния. Так что относитесь к листам действий как к перекрестку! Обычно сообщения нет, а заголовок отображается как текст размером с заголовок.
let action = UIAlertController(title: "What do you want to do with the message",
message: nil,
preferredStyle: .actionSheet)
action.addAction(UIAlertAction(title: "Cancel", style: .cancel))
for act in ["Save", "Post", "Discard"] {
action.addAction(UIAlertAction(title: act, style: .default, handler: nil))
}
self.present(action, animated: true)
Приведенный выше код будет работать для iPhone, но выйдет из строя во время выполнения для iPad, потому чтоUIPopoverPresentationController
будет отвечать за оповещение, и в это время он ни на что не ссылается. Поэтому, чтобы избежать этого, вам придется предоставить следующий фрагмент кода его обязательный
if let pop = action.popoverPresentationController {
let v = sender as! UIView
pop.sourceView = v
pop.sourceRect = v.bounds
}
Кроме того, в случае нажатия iPad в любом месте за пределами всплывающего окна оно будет отклонено, а обработчик завершения .cancel
кнопка действия будет вызвана.
Надеюсь, что это поможет:) При этом, прокомментируйте ниже, если у вас есть какие-либо сомнения
У меня есть еще один трюк. Предположим, у вас есть 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(). Надеюсь, поможет.
Я создал одноэлементный класс, чтобы его было удобно использовать из любого места в вашем приложении: 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.")
Свифт 3
Ниже приведен простой пример того, как создать простое оповещение с помощью одной кнопки с помощью Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
В вышеприведенном примере обратный вызов дескриптора действия был опущен, поскольку поведение по умолчанию для представления предупреждения с одной кнопкой должно исчезать при нажатии кнопки.
Вот как создать еще одно действие, которое можно добавить к предупреждению с помощью "alert.addAction(action)". Различные стили:.default, .destructive и.cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
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")
}
}
}
}
Или просто сделай это
let alert = UIAlertController(title: "Alert", message: "Saved Successfully", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
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)
}
Вы можете использовать это простое расширение с n количеством кнопок и связанных действий swift4 и выше
extension UIViewController {
func popupAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (index, title) in actionTitles.enumerated() {
let action = UIAlertAction(title: title, style: .default, handler: actions[index])
alert.addAction(action)
}
self.present(alert, animated: true, completion: nil)
}
}
Вы можете использовать это как,
self.popupAlert(title: "Message", message: "your message", actionTitles: ["first","second","third"], actions:[
{action1 in
//action for first btn click
},
{action2 in
//action for second btn click
},
{action3 in
//action for third btn click
}, nil])
Я получил следующее UIAlertView
код инициализации для компиляции без ошибок (я думаю, что последняя, varadic часть сложна, возможно). Но я должен был убедиться, что класс 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, делегат: MyViewController, cancelButtonTitle: String, otherButtonTitles: String)'
Как уже упоминалось, вам следует перейти на UIAlertController, если вы можете использовать iOS 8.x+. Для поддержки iOS 7 используйте приведенный выше код (iOS 6 не поддерживается Swift).
В 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)
@IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Попробуй это
SWIFT 4: Просто создайте расширение для UIViewController следующим образом:
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)
}
}
Теперь в вашем viewcontroller напрямую вызовите вышеуказанную функцию, как если бы они были предоставлены UIViewController.
yourViewController.showSucsessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
Причина, по которой это не работает, потому что какое-то значение, которое вы передали функции, неверно. Swift не любит Objective-C, вы можете указывать nil для аргументов типа класса без каких-либо ограничений (может быть). Аргумент otherButtonTitles определяется как необязательный, тип которого не имеет (?) В конце. поэтому вы должны передать ей конкретное значение.
Используйте этот код для отображения предупреждений
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)
// Общий класс для 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
Попробуй это. Поместите сильфон в кнопку.
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)
на 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)
Ниже приведен многократно используемый код для представления предупреждений и таблицы действий. Просто напишите одну строку, чтобы показать предупреждение в любом месте приложения
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)
}
}
}
}
Использование:
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)
}
}
}