Giter Club home page Giter Club logo

lkalertcontroller's Introduction

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.

lkalertcontroller's People

Contributors

abrahamdone avatar adarhef avatar akwilliamson avatar hardikdevios avatar jamesperlman avatar kevinmanncito avatar magnusottosson avatar nitrag avatar shanelk avatar skofgar avatar unknownjoe796 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  avatar  avatar  avatar

Watchers

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

lkalertcontroller's Issues

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

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

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

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

LKAlertController.bundle: No such file or directory

There seem to be an issue in the latest beta of cocoa pods (1.0.0.beta.6) causing the resource_bundles to create a path to the bundle file that is not correct.

Read more here: CocoaPods/CocoaPods#5034

It seems like LKAlertController does not have any assets so the resource_bundles directive can be removed and this could be a workaround for this issue? I have created a pull request for this that seems to solve the issue for now.

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

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.

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.