An easy to use UIAlertController builder for swift

Overview

LKAlertController

Circle CI Version License Platform

An easy to use UIAlertController builder for swift

Features

  • Short and simple syntax for creating both Alerts and ActionSheets from UIAlertController
  • String together methods to build more complex alerts and action sheets

Basic Usage

Alert

Alert(title: "Title", message: "Message")
	.addAction("Cancel")
	.addAction("Delete", style: .Destructive, handler: { _ in
		//Delete the object
	}).show()

Action Sheet

ActionSheet(title: "Title", message: "Message")
	.addAction("Cancel")
	.addAction("Delete", style: .Destructive, handler: { _ in
		//Delete the object
	}).show()

Detailed Usage

There are two seperate classes for creating UIAlertControllers, Alert, and ActionSheet. These are used to simplify the creation of the controller. Both can be initialized with or without both a title and message.

Alert()
ActionSheet()

Alert(title: "My title")
ActionSheet(title: "My title")

Alert(message: "My message")
ActionSheet(message: "My message")

Alert(title: "My title", message: "My message")
ActionSheet(title: "My title", message: "My message")

Add various actions to the controller using addAction. By default the button will be styled Cancel, but this can be configured on a per button basis, along with the handler that is called if the button is clicked. The possible styles are Cancel, Default, and Destructive. These methods can be strung together to add more buttons to the controller.

ActionSheet()
	.addAction("Cancel")
	.addAction("Save", style: .Default) {
		saveTheObject()
	}
	.addAction("Delete", style: Destructive) {
		deleteTheObject()
	}

The controller can be presented by calling show(). It will be animated by default.

Alert()
	.addAction("Okay")
	.show()
	
ActionSheet()
	.addAction("Delete", style: .Destructive) {
		delete()
	}
	.addAction("Cancel")
	.show(animated: true) {
		controllerWasPresented()
	}

Alert Specific Configuration

There is a shortcut on alerts to show with an okay button: showOkay

Alert(title: "Stuff has happened").showOkay()

You can also add your own shortcut show method. The following adds a showNevermind button that adds a Nevermind button and shows the alert.

extension Alert {
	///Shortcut method for adding a nevermind button and showing the alert
	public func showNevermind() {
		addAction("Nevermind", style: .Cancel, preferredAction: false, handler: nil)
		show()
	}
}

Text fields can also be added to alerts. To add a text field, initialize a text field first, and configure it, then pass it in with the alert. Note that text fields must be initialized as var rather than let

var textField = UITextField()
textField.placeholder = "Password"
textField.secureTextEntry = true

Alert().addTextfield(&textField).showOkay()

You can also configure the preferredAction property on an alert. This will highlight the text of the action, and pressing the return key on a physical keyboard will trigger this action.

Alert()
	.addAction("Okay", style: .Default, preferredAction: true)
	.show()

ActionSheet Specific Configuration

If presenting on iPad, ActionSheets need to be configured with where it is presenting from. This is done by using the setBarButtonItem or setPresentingSource function. Note that this has no effect on iPhone, so it is safe, and recommended, to call this method if your app supports both iPad and iPhone.

ActionSheet()
	.addAction("Delete", style: .Destructive) {
		delete()
	}
	.addAction("Cancel")
	.setBarButtonItem(navigationController.rightBarButtonItem)
	.show(animated: true) {
		controllerWasPresented()
	}
	
ActionSheet()
	.addAction("Delete", style: .Destructive) {
		delete()
	}
	.addAction("Cancel")
	.setPresentingSource(buttonThatWasPressed)
	.show(animated: true) {
		controllerWasPresented()
	}

##Testing

You can add an override for the show method to make it easy to add unit tests for your alerts.

func testDeleteOpensConfirmationAlert() {
	let expectation = expectationWithDescription("Show override")

	LKAlertController.overrideShowForTesting { (style, title, message, actions, fields) -> Void in 
		
		XCTAssertEquals(title, "Are you sure you want to delete?", "Alert title was incorrect")
		
		expectation.fulfill()
	}
	
	model.delete()
	
	//If the override is never called, and the expectation is not fulfilled, the test will fail
	waitForExpectations(0.5, handler: nil)
}

This will allow you to test the controller was presented as well as the title, message, actions and fields of the alert or action sheet.

Installation

LKAlertController is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "LKAlertController"

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate LKAlertController into your Xcode project using Carthage, specify it in your Cartfile:

github "lightningkite/LKAlertController"

Run carthage update to build the framework and drag the built LKAlertController.framework into your Xcode project.

Issues Questions and Contributing

Have an issue, or want to request a feature? Create an issue in github.

Want to contribute? Add yourself to the authors list, and create a pull request.

Author

Erik Sargent, [email protected]

License

LKAlertController is available under the MIT license. See the LICENSE file for more info.

Comments
  • Attempt to present UIAlertController on view not in the window hierarchy

    Attempt to present UIAlertController on view not in the window hierarchy

    Hiya,

    I've been looking for a nice method chain replacement for messy UIAlertController code for a while, so I gave yours a go! Unfortunately, I've run into a problem the first place I've tried to use it. =[ As part of performing Facebook login, I present a very simple dialog when all else fails as follows:

    Alert(title: "Error", message: "Unable to log in using Facebook. Please check your internet connection and try again.")
    .showOkay()
    

    This is called as the final part of the async callback chain (when the user has initiated FB login and it fails) and gives me the following error:

    Warning: Attempt to present <UIAlertController: 0x7fe3d35df020> on <FBSDKContainerViewController: 0x7fe3d5935af0> whose view is not in the window hierarchy!

    I'm guessing that the FBSDKContainer view controller is either being dismissed or isn't the right place to be launching this alert from. I've had a brief look at the logic used to select the controller and it looks sane... but I'm not exactly an expert on this. =/ Not sure where to go from here other than pull it out unless you have any ideas?

    Happy to help try and diagnose. I really like the simplicity of your approach.

    Kind regards, Andrew

    opened by afladmark 9
  • Add textfields to alert

    Add textfields to alert

    This adds simple convenience methods for adding textfields to a controller. Users can opt for a default textfield, optionally include placeholder text, or optionally configure the textfield for secure text entry.

    opened by akwilliamson 6
  • Cancel button always on left

    Cancel button always on left

    I can't get the Cancel button to be on the right. I tried switching the order of addAction and I also played around with addAction(String) vs addAction(String, style, handler).

           Alert(title: "Add", message: "test")
                    .addTextField(&nameField)
                    .addTextField(&descriptionField)
                    .addAction("Save", style: .default, handler: { _ in
                        print(nameField.text!)
                        print("Description: ", descriptionField.text!)
                    })
                    .addAction("Cancel")
                    .show()
    

    From Human Interface Guideline: In a two-button alert that proposes a potentially risky action, the button that cancels the action should be on the right (and light-colored). In a two-button alert that proposes a benign action that people are likely to want, the button that cancels the action should be on the left (and dark-colored).

    opened by nitrag 5
  • Update README.md for using text fields in alerts

    Update README.md for using text fields in alerts

    This includes instructions for variations on text field initialization and chaining text fields with other Alert methods. Note: Don't merge this PR until https://github.com/lightningkite/LKAlertController/pull/18 is merged.

    opened by akwilliamson 4
  • Styling

    Styling

    What do you think about adding functionality for styling? e.g. adding background color and tint color functionality? I'm not exactly sure what is and is not against the Apple guidelines for alerts.

    opened by akwilliamson 3
  • Add Required(Bool) to Textfield

    Add Required(Bool) to Textfield

    Adding the required option for addTextField(). This will make the preferredAction action button disabled until there is text input.

    Use case: You have an Alert+Textfield to name an object before saving, the name cannot be blank and you don't want to dismiss/reinit an alert to prompt the user for input again.

    .addTextField(&nameField, required: true )
    

    Note: only one required field is supported.

    OP: Please check variable declarations, I'm new to iOS, feedback appreciated!

    opened by nitrag 1
  • Require text in UITextField

    Require text in UITextField

    Loving this controller!

    Can we only enable the "Save" button if the textfield has input? I think it would require exposing the UIAlertViewController's primary action? Is that ok?

    Something like:

    @discardableResult
        public func addTextField( _ textField: inout UITextField, required: Bool = false) -> Alert {
    		var field: UITextField?
    		
            alertController.addTextField { [unowned textField] (tf: UITextField!) -> Void in
                tf.text = textField.text
                tf.placeholder = textField.placeholder
                tf.font = textField.font
                tf.textColor = textField.textColor
                tf.isSecureTextEntry = textField.isSecureTextEntry
                tf.keyboardType = textField.keyboardType
                tf.autocapitalizationType = textField.autocapitalizationType
                tf.autocorrectionType = textField.autocorrectionType
                
                field = tf
            }
    		
    		if let field = field {
    			textField = field
    		}
            
            if(required){
                NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
                    self.action.isEnabled = field?.text!.length > 0
                }
            }
            
            return self
        }
    

    based off: http://stackoverflow.com/questions/30596851/how-do-i-validate-textfields-in-an-uialertcontroller

    opened by nitrag 1
  • Carthage update fails

    Carthage update fails

    After upgrading to Xcode 8.1 (now with Swift 3.0.1) I had to rebuild LKAlertController, so I used carthage update. codesign failed, and it has something to do with the cocoa pod tests.

    Here are the relevant lines from the carthage-xcodebuild.xxxxxx.log file:

    Signing Identity:     "-"
    
    /usr/bin/codesign --force --sign - --timestamp=none /Users/home/Library/Developer/Xcode/DerivedData/LKAlertController-gfxpomyboovzwidrotfexklagyqa/Build/Products/Release-iphonesimulator/Pods-LKAlertController_Tests/LKAlertController.bundle
    /Users/home/Library/Developer/Xcode/DerivedData/LKAlertController-gfxpomyboovzwidrotfexklagyqa/Build/Products/Release-iphonesimulator/Pods-LKAlertController_Tests/LKAlertController.bundle: bundle format unrecognized, invalid, or unsuitable
    Command /usr/bin/codesign failed with exit code 1
    

    I think the key here is .../Pods-LKAlertController_Tests/LKAlertController.bundle: bundle format unrecognized, invalid, or unsuitable

    I got around this by forking your repo and removing the Pods-LKAlertController_Tests scheme.

    If anyone else needs a hot fix, use

    github "JamesPerlman/LKAlertController" "patch-1"

    in your Cartfile.

    I'm not sure how else to get around this, but I didn't spend too much time trying to figure this out.

    Am I the only one who uses Carthage and this framework? :P

    opened by JamesPerlman 1
  • Updated to Swift 3 (verify modification)

    Updated to Swift 3 (verify modification)

    Significant change on line 287 in method:

    public func addTextField(inout textField: UITextField) -> Alert {
    

    to

    public func addTextField(_ textField: UITextField) -> Alert {
    

    Why was the textfield inout? From my understanding this only makes sense if you want to modify an Alert's value while it's being displayed?

    opened by skofgar 1
  • Can't invoke addAction(_:style:handler) on ActionSheet instance

    Can't invoke addAction(_:style:handler) on ActionSheet instance

    When trying to invoke addAction on ActionSheet class instance with parameters title, style and handler, Xcode reports:

    Ambiguous use of addAction(_:style:handler)

    ActionSheet().addAction("Test", style: .Default, handler: { _ in print("Test") }).show()

    I've tried to use LKAlertController instance and it works:

    LKAlertController(style: .ActionSheet).addAction("Test", style: .Default, handler: { _ in print("Test") }).show()

    opened by paweljankowski 1
  • Possible to create UIAlertAction and add to the Sheet?

    Possible to create UIAlertAction and add to the Sheet?

    For example

    let action = UIAlertAction(title: "Sort By Month", style: .default) { (action) in } action.isEnabled = false ActionSheet(title: nil, message: nil).addAction(action).addAction("Dismiss").show()

    opened by nitish07 0
Releases(1.6.0)
Owner
Lightning Kite
Lightning Kite
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
Use UIAlertController like a boss.

Description Requirements Installation CocoaPods Carthage Usage License Description CatAlertController is a high level manager object that with chainin

Kcat 8 Feb 8, 2022
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
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
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
An easier constructor for UIAlertController. Present an alert from anywhere.

ALRT An easier constructor for UIAlertController. Present an alert from anywhere like this. ALRT.create(.alert, title: "Alert?").addOK().addCancel().s

Masahiro Watanabe 97 Nov 11, 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 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
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
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
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
UIAlertController with continuity.

CuckooAlert Allow multiple use of presentViewController to UIAlertController. You may be disappointed from this. Do you imagine that cuckoo spit out s

Jay Choi 5 Feb 2, 2020
UIPicker inside a UIAlertController

DPPickerManager UIPicker inside a UIAlertController HOW TO USE : // Strings Picker let values = ["Value 1", "Value 2", "Value 3", "Value 4"] DPPickerM

Prioregroup.com 45 May 30, 2022
An easier constructor for UIAlertController. Present an alert from anywhere.

ALRT An easier constructor for UIAlertController. Present an alert from anywhere like this. ALRT.create(.alert, title: "Alert?").addOK().addCancel().s

Masahiro Watanabe 97 Nov 11, 2022