Cancel Button in UIAlertController with UIAlertControllerStyle.ActionSheet
Asked Answered
A

4

23

I want to add a separated cancel button to my UIAlert.

I know how to do it with UIActionSheet but it should also be possible with UIAlert, right?

var sheet: UIActionSheet = UIActionSheet();
    let title: String = "...";
    sheet.title  = title;
    sheet.delegate = self;
    sheet.addButtonWithTitle("Cancel");
    sheet.addButtonWithTitle("...")
    sheet.cancelButtonIndex = 0;
    sheet.showInView(self.view);

This will have a ... button and a cancel button which is separated.

So does anyone know how to do this with

    var alert = UIAlertController(title: "...", message: "....", preferredStyle: UIAlertControllerStyle.ActionSheet)

?

I'm new to xcode and swift so sorry if this question is dumb or anything...

Amalee answered 16/11, 2014 at 10:37 Comment(0)
Q
60

Its really simple, but works a bit differently to how they used to work. Now you add "actions" to your alerts. These actions are then represented by buttons on the device.

alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

Above is the code needed for a simple cancel button - bear in mind that dismissal of the alert is done automatically so don't put that in your handler. Should you then want to create another button which does something, use the code below:

alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.Default, handler: { action in
        println("This button now calls anything inside here!")
    }))

Hopefully I have understood your question and this answers what you were asking. I will also add that after you have added all of the "actions", you present the alert using the code below:

self.presentViewController(alert, animated: true, completion: nil)

Hope this helps!

Quinate answered 16/11, 2014 at 11:48 Comment(4)
While this works, it doesn't answer the part of his question about adding a separate for the cancel button, like UIActionSheet does. UIAlertController doesn't add a separator before the cancel button like UIActionSheet.Encompass
@PsychoDad you're quite right! - I must have misunderstood the question when i first answered it. I don't know a way of creating a separator without writing a custom UIAlert so will not be able to amend this question i'm afraid.Quinate
If you add action with style set to UIAlertActionStyle.Cancel, separator is added automatically.Filter
@MiroslavHrivik No, the separator is not added even if the style is set to cancel.Parlin
S
9

I wanted to go ahead and provide a specific answer for a specific question. The user asked about the implementation of a "cancel" button, not a default button. Check out the answer below!

let alertController = UIAlertController(title: "Select one", message: "Hey! Press a button", preferredStyle: .actionSheet)

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

alertController.addAction(cancelAction)

self.present(alertController, animated: true, completion: nil)
Softshoe answered 29/1, 2017 at 4:3 Comment(1)
This is the right response which shows how to add the separator thanks to style: .cancelMorrissette
S
0

This might be the worst coded answer you would have seen, but I was able to meet your requirement by trying this:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UILabel *alertLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, alertController.view.frame.size.width, 2)];
alertLine.backgroundColor=[UIColor blackColor];
[alertController.view.preferredFocusedView addSubview:alertLine];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self.navigationController presentViewController:alertController animated:YES completion:nil];
Superphosphate answered 11/5, 2016 at 20:13 Comment(1)
The problem here is that the question is tagged "swift", not "objective-c". :)Candelabra
C
0

Incredibly simple extensions every app needs:

Illustrates how to add cancel button:

extension UIViewController {
    
    ///Trivial alert, with completion if you need it.
    func verySimple(alert: String, completionOnMain: (()->())? = nil) {
        
        let alert = UIAlertController(title: "", message: alert, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
            DispatchQueue.main.async { completionOnMain?() }
        })
        present(alert, animated: false, completion: nil)
    }
    
    ///Trivial alert, with completion if you need it. Feat. cancel button.
    func verySimpleCancellable(alert: String, completionOnMain: (()->())? = nil) {
        
        let alert = UIAlertController(title: "", message: alert, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
            DispatchQueue.main.async { completionOnMain?() }
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: false, completion: nil)
    }
}

It's then this easy to add an alert anywhere

verySimpleCancellable(alert: "Run the test function?") {
    self.testFunction()
}

enter image description here

Or

verySimple(alert: "Run the test function?") {
    self.testFunction()
}

enter image description here

Or just a message

verySimple(alert: "It seemed to work")

enter image description here

The effect of the one extra line of "cancel button" code is apparent.

Collectanea answered 24/5 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.