Coder Social home page Coder Social logo

mshrwtnb / alrt Goto Github PK

View Code? Open in Web Editor NEW
96.0 4.0 11.0 125 KB

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

License: MIT License

Objective-C 3.63% Swift 91.20% Ruby 5.17%
uialertcontroller swift alert uialertview uialertaction

alrt's Introduction

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.

alrt's People

Contributors

mono0926 avatar mshrwtnb avatar shimesaba9 avatar stnamco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

alrt's Issues

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

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

画面遷移のあるアプリで、遷移後の画面で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

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.