An easier constructor for UIAlertController. Present an alert from anywhere.

Overview

ALRT

An easier constructor for UIAlertController. Present an alert from anywhere like this.

ALRT.create(.alert, title: "Alert?").addOK().addCancel().show()

Table of Contents

Features

  • Chainable UIAlertController Setup Methods
  • Support .alert and .actionSheet UIAlertController.Style
  • Support UITextfield UIAlertAction(.alert only)
  • Returns Result whether an alert is successfully displayed. In other words, Unit Testable.

Requirements

  • Xcode 10.2+
  • Swift 5.0
  • iOS 9.0+

Installation

Carthage

github "mshrwtnb/ALRT" ~> 1.3.7

Cocoapods

pod repo update
pod 'ALRT', '~> 1.3.7'

Usage

Basics

.alert

import ALRT

// Instantiate an .alert-type UIAlertController with OK and Cancel actions. Finally, present the alert by calling `show()`.
ALRT.create(.alert, title: "Title", message: "Message").addOK().addCancel().show()

.actionSheet

// Instantiate an .actionSheet-type UIAlertController.
ALRT.create(.actionSheet, message: "Action Sheet")
    .addAction("Option A")
    .addAction("Option B")
    .addDestructive("Destructive Option")
    .show() 

Action Types

Each action comes with different UIAlertAction.Style.

ALRT.create(.alert, title: "Action Types?")
    .addAction("🏂") // .default if not specified
    .addOK() // .default
    .addCancel("") // .cancel
    .addDestructive("💣") // .destructive
    .show()

Custom Title

OK and Cancel actions have default titles in English; "OK" and "Cancel". Here, we're overriding the titles in Japanese.

ALRT.create(.alert, title: "Actions In Japanese?").addOK("オーケー").addCancel("キャンセル").show()

Action Handling

Each action has handler that is called when user taps the action. The closure takes two parameters: UIAlertAction and [UITextField]?. The former is self-explanatory. The latter is present if text field(s) is/are added to the alert.

ALRT.create(.alert, title: "Action Handling")
    .addOK() { action, textFields in
        print("\(action.title!) tapped")
    }
    .show()

Result Handling

show() has a completion handler that takes Result. You can ensure if the alert was shown successfully or not. This is useful for unit tests.

ALRT.create(.alert, title: "Result Handling")
    .addOK()
    .show() { result in
        switch result {
        case .success:
            print("Alert is successfully shown")
        case .failure(let error):
            print("Error occurred. \(error.localizedDescription)")
        }
    }

TextField(s)

Textfield(s) can be added to an alert in an use-case such as login.

enum TextFieldIdentifier: Int {
    case username
    case password
}

ALRT.create(.alert, title: "Enter your credentials")
    // Configure textfield
    .addTextField { textfield in
        textfield.placeholder = "Username"
        textfield.tag = TextFieldIdentifier.username.rawValue
    }
    .addTextField() { textField in
        textField.placeholder = "Password"
        textField.isSecureTextEntry = true
        textField.tag = TextFieldIdentifier.password.rawValue
    }
    // If an user selects "Login", textfields above are retrieved in the trailing closure. Distinguish one from another with a tag or identifier.
    .addAction("Login") { _, textfields in
        for textField in textfields ?? [] {
            if let identifier = TextFieldIdentifier(rawValue: textField.tag) {
                switch identifier {
                case .username:
                    // Extract username
                case .password:
                    // Extract password
                }
            }
        }
    }
    .addCancel()
    .show()

Changing source ViewController to present from

Although ALRT can present an alert anywhere, you might want to specify a source view controller for some reason. This can be done easily by passing a view controller to show().

ALRT.create(.alert, title: "Source?")
    .addOK()
    .show(self) // self = source view controller

Default Configuration

Set default tintColor and titles for OK and Cancel buttons.

ALRT.defaultConfiguration = .init(
    tintColor: UIColor.blue,
    okTitle: "OK👍",
    cancelTitle: "Cancel👎"
)

License

ALRT is released under the MIT license. See LICENSE for details.

Comments
  • iOS13で、アラートが表示されなくなる場合がある

    iOS13で、アラートが表示されなくなる場合がある

    iOS 13にて、UIViewControllerをセットせずにshow()をコールすると、下記のような現象が起こるようです。 お手数ですが、確認をお願いできませんでしょうか。

    現象

    1.デバッグに以下の警告が表示される

    Keyboard cannot present view controllers (attempted to present <UIAlertController: 0x------->

    2.アラートが表示できなくなる

    アラートを頻繁に表示していると、何かのタイミングで、それ以降、アラートが表示できなくなります。 詳細な再現条件は分かっていませんが、下記のコードのように、テキストフィールドを持つアラートを表示し、キーボードが表示されているタイミングで、OK等のクロージャから次のアラートを表示すると、私の環境(6世代iPad, iPadOS 13.4.1)ではほぼ再現します。 ただ、頻度は低いですが、キーボードを表示しなくても、同じ現象が発生する場合があります。 この現象が発生すると、以降、アラートを表示しようとすると、デバッグエリアに、下記のような警告が表示されます。

    [View] First responder error: non-key window attempting reload - allowing due to manual keyboard (first responder window is <UIRemoteKeyboardWindow: 0x105869c00; frame = (0 0; 768 1024); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x28157ed00>>, key window is <UITextEffectsWindow: 0x1049365e0; frame = (0 0; 768 1024); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x2815c6040>>)

    ALRT.create(.alert, title: "テスト", message: "テスト")
    	.addTextField { textfield in
    		textfield.placeholder = ""
    		textfield.tag = 0
    	}
    	.addOK() { action, textFields in
    		// このアラートは表示されず、以降、アラートが表示できなくなる
    		ALRT.create(.alert, title: "エラー", message: "エラー").addOK().show()
    	}
    	.addCancel()
    	.show()
    

    3.アラートのテキストエリアにフォーカスがあたらず、キーボードが自動表示されない

    原因

    UIApplication.topMostViewController()が、キーボード用のWindow(UIRemoteKeyboardWindow)を返しているのが原因ではないでしょうか。 下記のように修正したところ、問題は発生しなくなりました。

    private extension UIApplication {
        func topMostViewController() -> UIViewController? {
    	let uiWindow: UIWindow? = {
    		for window in windows.reversed() {
    			if NSStringFromClass(type(of: window)) == "UIWindow" {
    				return window
    			}
    		}
    		return windows.last
    	}()
    		
    	guard let keyWindow = uiWindow else {
                return nil
            }
            return keyWindow.rootViewController?.topMostViewController()
        }
    }
    
    bug wip 
    opened by yuhnag 2
  • Constraint issue with alert actionsheet.

    Constraint issue with alert actionsheet.

    Error

    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
    2020-04-23 15:21:48.556790-0600 Banky[71185:1795813] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    	Probably at least one of the constraints in the following list is one you don't want. 
    	Try this: 
    		(1) look at each constraint and try to figure out which you don't expect; 
    		(2) find the code that added the unwanted constraint or constraints and fix it. 
    (
        "<NSLayoutConstraint:0x6000032b6080 UIView:0x7fb0ba45f9e0.width == - 16   (active)>"
    )
    
    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x6000032b6080 UIView:0x7fb0ba45f9e0.width == - 16   (active)>
    

    This is what I'm calling and the above warning occurs.

            ALRT.create(.actionSheet)
                .addAction("Terms of Use") { _, _ in
                    self.performSegue(withIdentifier: "termsToWebView", sender: nil)
                }
            .addAction("Privacy Policy") { _, _ in
                self.performSegue(withIdentifier: "privacyToWebView", sender: nil)
            }
            .addCancel()
            .show()
    
    bug 
    opened by trevorphillipscoding 2
  • 画面遷移後アラートが表示されない。

    画面遷移後アラートが表示されない。

    画面遷移のあるアプリで、遷移後の画面でALRTを使おうとすると、以下のようなエラーが出てアラートが表示されません。 Demo[26163:424735] Warning: Attempt to present <UIAlertController: 0x7fd9e5044a00> on <Demo.FirstViewController: 0x7fd9e7c07930> whose view is not in the window hierarchy!

    FirstViewControllerといのは、demoのプロジェクトでDemoViewControllerに遷移するViewControllerです。

    表示するViewControllerがうまく指定できていないと思うのですが、対策はあるでしょうか? 問題が発生するDemoを含んだZipを添付します。 ALRT-master_edited.zip

    opened by HiroshiOshiro 2
  • Added default configuration

    Added default configuration

    This PR enables ALRT to use defaultConfiguration. By setting defaultConfiguration, ALRT can ...

    1. Show an UIAlertController with user-defined tint color
    2. Show OK and Cancel buttons with user-defined titles

    See https://github.com/mshrwtnb/ALRT/pull/15/files#diff-f748f6c5192632893abcb48efd218a3fR105-R140 to understand how to use defaultConfiguration and its expected behavior.

    enhancement 
    opened by mshrwtnb 1
  • remove deprecated property

    remove deprecated property

    thanks for creating a useful library. I found a deprecated property. if you have time, please check it out.

    https://developer.apple.com/documentation/uikit/uiapplication/1622924-keywindow

    opened by stNamco 0
Releases(1.3.7)
Owner
Masahiro Watanabe
Masahiro Watanabe
Swift UI Kit to present clean modal/alert

CleanyModal is a good way to use UI-Customised alerts with ease Features Present some kind of clean alerts (With same API as UIAlertViewController) Ad

Lory Huz 487 Dec 2, 2022
PMAlertController is a great and customizable alert that can substitute UIAlertController

PMAlertController is a small library that allows you to substitute Apple's uncustomizable UIAlertController, with a beautiful and totally customizable

Paolo Musolino 2.5k Jan 3, 2023
A simple, customizable popup dialog for iOS written in Swift. Replaces UIAlertController alert style.

Introduction Popup Dialog is a simple, customizable popup dialog written in Swift. Features Easy to use API with hardly any boilerplate code Convenien

Orderella Ltd. 3.8k Dec 20, 2022
PMAlertController is a great and customizable alert that can substitute UIAlertController

PMAlertController is a small library that allows you to substitute Apple's uncustomizable UIAlertController, with a beautiful and totally customizable

Paolo Musolino 2.5k Jan 3, 2023
Simple Alert View written in Swift, which can be used as a UIAlertController. (AlertController/AlertView/ActionSheet)

DOAlertController Simple Alert View written in Swift, which can be used as a UIAlertController replacement. It supports from iOS7! It is simple and ea

Daiki Okumura 406 Sep 5, 2022
A simple custom popup dialog view for iOS written in Swift. Replaces UIAlertController alert style.

A simple custom popup dialog view for iOS written in Swift. Replaces UIAlertController alert style.

donggyu 5 Jan 26, 2022
Present a sheet ViewController easily and control ViewController height with pangesture

PanControllerHeight is designed to present a sheet ViewController easily and control ViewController height with pangesture.

null 2 May 3, 2022
LBBottomSheet gives you the ability to present a controller in a kind of

LBBottomSheet Installation Swift Package Manager To install using Swift Package Manager, in Xcode, go to File > Add Packages..., and use this URL to f

Lunabee Studio 48 Dec 9, 2022
Swifty, modern UIAlertController wrapper.

Alertift Alertift.alert(title: "Alertift", message: "Alertift is swifty, modern, and awesome UIAlertController wrapper.") .action(.default("❤️"))

Suguru Kishimoto 287 Jan 7, 2023
Advanced usage of UIAlertController and pickers based on it: Telegram, Contacts, Location, PhotoLibrary, Country, Phone Code, Currency, Date...

Alerts & Pickers Advanced usage of native UIAlertController with TextField, TextView, DatePicker, PickerView, TableView, CollectionView and MapView. F

RV 5.5k Dec 22, 2022
Easy Swift UIAlertController

EZAlertController Easy Swift UIAlertController One line setup for all UIAlertControllers Button action with closures instead of selectors Easily custo

Kan Yilmaz 366 Sep 14, 2022
Simple UIAlertController builder class in Swift.

Kamagari Simple UIAlertController builder class in Swift. Features AlertBuilder class to simply build UIAlertController by using method chaining UIAle

Kazunobu Tasaka 78 Nov 29, 2022
A customizable, full-feature, lightweight iOS framework to be used instead of UIAlertController.

A customizable, full-feature, lightweight iOS framework to be used instead of UIAlertController.

Ali Samaiee 11 Jun 6, 2022
Advanced usage of UIAlertController and pickers based on it: Telegram, Contacts, Location, PhotoLibrary, Country, Phone Code, Currency, Date...

Alerts & Pickers Advanced usage of native UIAlertController with TextField, TextView, DatePicker, PickerView, TableView, CollectionView and MapView. F

RV 5.5k Dec 26, 2022
This is an iOS control for selecting a date using UIDatePicker in an UIAlertController like manner

RMDateSelectionViewController This framework allows you to select a date by presenting an action sheet. In addition, it allows you to add actions arro

Roland Moers 1.2k Dec 13, 2022
This is an iOS control for presenting any UIView in an UIAlertController like manner

RMActionController This framework allows you to present just any view as an action sheet. In addition, it allows you to add actions around the present

Roland Moers 542 Dec 5, 2022
This is an iOS control for selecting something using UIPickerView in an UIAlertController like manner

RMPickerViewController This framework allows you to pick something with a picker presented as an action sheet. In addition, it allows you to add actio

Roland Moers 382 Dec 19, 2022
An easy to use UIAlertController builder for swift

LKAlertController An easy to use UIAlertController builder for swift Features Short and simple syntax for creating both Alerts and ActionSheets from U

Lightning Kite 97 Feb 8, 2022
Customizable replacement for UIAlertController

ActionSheet Customizable replacement for UIAlertController. Requirements Installation Swift Package Manager The Swift Package Manager is a tool for au

Horizontal Systems 0 Oct 6, 2022