Skip to content

Instantly share code, notes, and snippets.

@chenr2
Last active August 29, 2015 14:25
Show Gist options
  • Save chenr2/77ec81fcc35b40916ee3 to your computer and use it in GitHub Desktop.
Save chenr2/77ec81fcc35b40916ee3 to your computer and use it in GitHub Desktop.
Swift UIAlertView for iOS 7 compatibility. Also demonstrates adding a TextField to the AlertView.

Using UIAlertView

UIAlertView is deprecated, so use it for iOS 7 compatibility. Otherwise, use UIAlertController.

let alertView = UIAlertView()
alertView.message = "here"
alertView.addButtonWithTitle("Ok")
alertView.show()

Add a TextField to UIAlertView

Set the alertViewStyle and the delegate.

let alertView = UIAlertView()
alertView.alertViewStyle = .PlainTextInput
alertView.title = "Title"
alertView.message = "Message"
alertView.addButtonWithTitle("Cancel")
alertView.addButtonWithTitle("Ok")
alertView.delegate = self
alertView.show()

You don't tell your class to conform to a protocol (no wonder this thing is deprecated!). Just implement this method, and have faith that it gets called. View.textFieldAtIndex(0) gives you a handle on the UITextField.

override func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
    switch buttonIndex{
    case 1:
        println("Ok")
        if let textField = View.textFieldAtIndex(0) as UITextField? {
            println("textField:: \(textField.text)")
        }
    case 0:
        println("Cancel")
    default:
        println("Default shouldn't get called")
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment