Make UIAlertView Button trigger function On Press - iphone

Currently I am using the following code to present a UIAlertView:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Today's Entry Complete"
message:#"Press OK to submit your data!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
How do I get it so that when 'OK" is pressed, it triggers a function, say -(void)submitData

NOTE:
Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.
Please check this out tutorial
"deprecated" means???
Objectvie C
.h file
#interface urViewController : UIViewController <UIAlertViewDelegate> {
.m file
// Create Alert and set the delegate to listen events
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Today's Entry Complete"
message:#"Press OK to submit your data!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
// Set the tag to alert unique among the other alerts.
// So that you can find out later, which alert we are handling
alert.tag = 100;
[alert show];
//[alert release];
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
// Is this my Alert View?
if (alertView.tag == 100) {
//Yes
// You need to compare 'buttonIndex' & 0 to other value(1,2,3) if u have more buttons.
// Then u can check which button was pressed.
if (buttonIndex == 0) {// 1st Other Button
[self submitData];
}
else if (buttonIndex == 1) {// 2nd Other Button
}
}
else {
//No
// Other Alert View
}
}
Swift
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)

If you are using multiple UIAlertView instances that are not declared in the class's interface you can also set a tag to identify instances in your delegate method, for example:
somewhere on top of your class file myClass.m
#define myAlertViewsTag 0
creating the UIAlertView:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"My Alert"
message:#"please press ok or cancel"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
alert.tag = myAlertViewsTag;
[alert show];
[alert release];
the delegate method:
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (alertView.tag == myAlertViewsTag) {
if (buttonIndex == 0) {
// Do something when cancel pressed
} else {
// Do something for ok
}
} else {
// Do something with responses from other alertViews
}
}

You need to set the delegate when allocating the alertview, then use one of the UIAlertViewDelegate methods to call your own method, for example:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Today's Entry Complete"
message:#"Press OK to submit your data!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self submitData];
}

You need to setup the delegate for your UIAlertView, before showing it. Then do the work in the delegate callback as such:
-(void)alertView:(UIAlertView*)alert didDismissWithButtonIndex:(NSInteger)buttonIndex;
{
if ([[alert buttonTitleAtIndex] isEqualToString:#"Do it"]) {
// Code to execute on Do it button selection.
}
}
My CWUIKit project over at https://github.com/Jayway/CWUIKit has an addition to UIAlertView that allow you to do the same thing but with blocks. Redusing the same operation for both creating, showing and handling the alert to this:
[[UIAlertView alertViewWithTitle:#"My Title"
message:#"The Message"
cancelButtonTitle:#"Cancel"
otherTitlesAndAuxiliaryActions:#"Do it",
^(CWAuxiliaryAction*a) {
// Code to execute on Do it button selection.
}, nil] show];

If you want to use blocks you can also use MKAdditions to achieve this easily even for multiple UIAlertViews.
Just use a code similar to this sample:
[[UIAlertView alertViewWithTitle:#"Test"
message:#"Hello World"
cancelButtonTitle:#"Dismiss"
otherButtonTitles:[NSArray arrayWithObjects:#"First", #"Second", nil]
onDismiss:^(int buttonIndex)
{
NSLog(#"%d", buttonIndex);
}
onCancel:^()
{
NSLog(#"Cancelled");
}
] show];
You can find more information in this tutorial: http://blog.mugunthkumar.com/coding/ios-code-block-based-uialertview-and-uiactionsheet

Little more clarification,
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//handles title you've added for cancelButtonTitle
if(buttonIndex == [alertView cancelButtonIndex]) {
//do stuff
}else{
//handles titles you've added for otherButtonTitles
if(buttonIndex == 1) {
// do something else
}
else if(buttonIndex == 2) {
// do different thing
}
}
}
Example,
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Need your action!"
message:#"Choose an option to continue!" delegate:self cancelButtonTitle:#"Not Need!"
otherButtonTitles:#"Do Something", #"Do Different", nil];
[alert show];
(it's iOS7 screenshot)

From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, its is also stated in depreciation message
UIAlertView is deprecated. Use UIAlertController with a preferredStyle
of UIAlertControllerStyleAlert instead
So you should use something like this
Objective C
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Yes, please"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle your yes please button action here
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:#"No, thanks"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:yesButton];
[alert addAction:noButton];
[self presentViewController:alert animated:YES completion:nil];
Swift
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)

Related

poptorootview when click on alerrtview ok

I have a home view ,when click on that it is going to another view again i am going to another view.when click on a button on that view a modalview will appear and then subsequently 3 more modal views when click on each modalview.when click on the final modalview an alert will appear and when click on that alert i want to show the root homeview.Is it possible
?
Display AlertView using given code snippet:
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message: #"Alert Message"
delegate: self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
Delegate Method implementation :
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
Sample Code given below:
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Alert Message?" message:#"Error......" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK"] autorelease];
[alert show];
The implemention alertView's delegate functions is given below
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
//cancel clicked ...do your action
}
else if (buttonIndex == 1)
{
//OK clicked
[self.navigationController popToViewController animated:YES];
}
}
just give the delegate in .h file and after in delegate method of alertview write bellow code..
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
[self.navigationController popToRootViewControllerAnimated:YES];///this line is important..
}
else{
// do your action...
}
}
i hope this answer is useful to you..
:)
int c=[self.navigationController.viewControllers count]-4;
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:c] animated:YES];

is there easy way to handle UIAlertView result without delegation?

I have a function that shows a UIAlertView with YES/NO buttons, and it is used only inside the function's scope so I dont want to implement a delegation to catch the user feedback.
Is there any way to know what button users clicked without implement UIAlertViewDelegate, something like:
[alert show];
if([alert indexOfClickedButton] == indexOfYes)
{
....
}
Or lambda expression as in Animation
There is no way to avoid delegation completely, but you could create a wrapper to that effect along these lines:
#interface MyAlertViewDelegate : NSObject<UIAlertViewDelegate>
typedef void (^AlertViewCompletionBlock)(NSInteger buttonIndex);
#property (strong,nonatomic) AlertViewCompletionBlock callback;
+ (void)showAlertView:(UIAlertView *)alertView withCallback:(AlertViewCompletionBlock)callback;
#end
#implementation MyAlertViewDelegate
#synthesize callback;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
callback(buttonIndex);
}
+ (void)showAlertView:(UIAlertView *)alertView
withCallback:(AlertViewCompletionBlock)callback {
__block MyAlertViewDelegate *delegate = [[MyAlertViewDelegate alloc] init];
alertView.delegate = delegate;
delegate.callback = ^(NSInteger buttonIndex) {
callback(buttonIndex);
alertView.delegate = nil;
delegate = nil;
};
[alertView show];
}
#end
(ARC is assumed, if you are not using it change delegate = nil to [delegate release].)
Usage would be something like:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"Yes or No?" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Yes",#"No", nil];
[MyAlertViewDelegate showAlertView:alert withCallback:^(NSInteger buttonIndex) {
// code to take action depending on the value of buttonIndex
}];
I have written a blog post about how to (and why) add block callbacks to alert views, action sheets and animations:
http://blog.innovattic.com/uikitblocks/
If you just want a working implementation of this you can download the sources files from GitHub:
https://github.com/Innovattic/UIKit-Blocks
Usage:
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"My easy alert"
message:#"Would you like to perform some kind of action?"
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[alert setHandler:^(UIAlertView* alert, NSInteger buttonIndex) {
NSLog(#"Perform some kind of action");
} forButtonAtIndex:[alert firstOtherButtonIndex]];
[alert show];
It's very easy. Say you have an alert, something like this:
//Alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"Yes or No?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Yes",#"No", nil];
[alert show];
You're going to need to add this method:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
A possible implementation of this method would look like this:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//Checks For Approval
if (buttonIndex == 1) {
//do something because they selected button one, yes
} else {
//do nothing because they selected no
}
}
You can do this using custom view which can be hidden and shown to avoid ActionSheets
UIView *AlertVw=[UIView alloc]initWithFrame:CGRect(x,y,w,h)]];
UIButton *SaveButton=[UIButton alloc]initWithFrame:CGRect(x,y,w,h)]];
[CustomButton setTitle:#"Ok" forState:UIControlStateNormal];
[SaveButton addTarget:self action:#selector(SaveClicked) forControlEvents:UIControlEventTouchUpInside];
UIButton *CancelButton=[UIButton alloc]initWithFrame:CGRect(x,y,w,h)]];
[CustomButton setTitle:#"Cancel" forState:UIControlStateNormal];
[CancelButton addTarget:self action:#selector(CancelClicked) forControlEvents:UIControlEventTouchUpInside];
[AlertVw addSubview:SaveButton];
[AlertVw addSubview:CancelButton];
[self.view addSubview:AlertVw];
-(void)SaveButton
{
//Code to apply on Save clicked
[AlertVw removeFromSuperView]; //Also you can use AlertView.hidden=YES;
}
-(void)CancelButton
{
//Code to apply on cancel clicked
[AlertVw removeFromSuperView]; //Also you can use AlertView.hidden=YES;
}
No need to derive the class. With Block, it is easy to get user selected button index.
typedef void(^AlertViewCallBackBlock)(NSInteger selectedIndex);
#interface ABC ()
#property (nonatomic, copy) AlertViewCallBackBlock alertViewBlock;
#end
#implementation
- (void)showAlert {
self.alertViewBlock = ^(NSInteger selectedIndex) {
if (selectedIndex == 1) {
}
};
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"Yes or No?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Yes",#"No", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
self.alertViewBlock(buttonIndex);
}
#end
Thanks Arkku. Here is the Swift version.
https://github.com/exchangegroup/alert-view-with-callback-swift
let alertView = UIAlertView(...)
AlertViewWithCallback().show(alertView) { alertView, buttonIndex in
println("You closed alert by tapping button #\(buttonIndex)")
}
UIAlertView is deprecated from iOS 8.0, a better solution will be using UIAlertController:
let alert = UIAlertController(title: "message", message: "Title", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "YES", style: .Default, handler: { (action) -> Void in
// Action for YES
}))
alert.addAction(UIAlertAction(title: "NO", style: .Default, handler: { (action) -> Void in
// Action for NO
}))
self.view.window!.rootViewController!.presentViewController(alert, animated: true, completion: nil)

Alert message for the button click in iphone sdk 4.3

I am beginner to xcode programming.Please tell me how to display the alert message when we are going to click the button in xcode-iphone-4.3
My Code is as follows,
- (IBAction)buttonPressed:(id)sender{
UIAlertView* mes=[[UIAlertView alloc] initWithTitle:#"Hello World!!!!!!"
message:#"This is the Iphone app" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[mes show];
[mes release];
Please help me regarding this.
-(IBAction)buttonOnePressed:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"Clicked button 1"
message: #"Alert Message here"
delegate: self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK",nil];
[alert setTag:1];
[alert show];
}
-(IBAction)buttonTwoPressed:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"Clicked button 2"
message: #"Alert Message here"
delegate: self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK",nil];
[alert setTag:2];
[alert show];
}
Below is the delegate method to track which button on Alertview is hit.
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1) { // UIAlertView with tag 1 detected
if (buttonIndex == 0)
{
NSLog(#"user pressed Button Indexed 0");
// Any action can be performed here
}
else
{
NSLog(#"user pressed Button Indexed 1");
// Any action can be performed here
}
}
else if (alertView.tag == 2) { // UIAlertView with tag 2 detected
if (buttonIndex == 0)
{
NSLog(#"user pressed Button Indexed 0");
// Any action can be performed here
}
else
{
NSLog(#"user pressed Button Indexed 1");
// Any action can be performed here
}
}
}
You can set tag to UIAlertView in case you have more than one UIAlertViews and can determine which UIAlertView button is clicked in its delegate method clickedButtonAtIndex using its respective tag.
In IBAction you have to write the code and give the Connections to the Button
Create the IBAction for your button and add the code for alert view in that method.

UIAlertView button tagging

Is there a way I can add a .tag to an UIAlertView button? Reason being, I'm adding a few dynamic buttons to the alert that will sometimes be in the alert and sometimes not. I figured the best way was to add a tag. Is there a better method for this?
The options that will ALWAYS be in the alert are Email, Save. And the 2 optional options are Tweet This and Facebook.
Thanks for any help in advance!
There is one method buttonTitleAtIndex for UIAlertView. Use that to find the button tapped by user.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonString = [alertView buttonTitleAtIndex:buttonIndex];
if( [buttonString isEqualToString:#"Facebook"] ){
// your code here
} else if( [buttonString isEqualToString:#"twitter"] ){
// your code here
}
}
You can also use tag proprerty:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info"
message:#"Info text"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert setTag:0];
Then in delegate:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (alertView.tag) {
case 1: {
...
break;
}
...
default:
break;
}

Alert view in iphone

I am new to iPhone application development. I want to design an alert view with 2 buttons: OK and Cancel. When the user touches the OK button, then I will print a message that says hello. When they touch the Cancel button, I will print cancel.
Please help; how do I do this?
To show the alert:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Do you want to say hello?"
message:#"More info..."
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Say Hello",nil];
[alert show];
[alert release];
To respond to whatever button was tapped:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(#"Cancel Tapped.");
}
else if (buttonIndex == 1) {
NSLog(#"OK Tapped. Hello World!");
}
}
For more information, see the UIAlertView Class Reference and the UIAlertView Delegate Protocol Reference.
since the chosen answer is deprecated, here is the new solution:
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"My Alert"
message:#"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
As shown in iOs Developer guide.
Show the alert with the following snippet
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Make an informed choice"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[alert show];
The delegate is set to self so when the alert is dismissed our own class will get a call back. The delegate must implement the UIAlertViewDelegate protocol.
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger) buttonIndex{
if (buttonIndex == 1) {
// Do it!
} else {
// Cancel
}
}
For Objective C:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"My Alert"
message:#"This is an action sheet."
preferredStyle:UIAlertControllerStyleAlert]; // 1
UIAlertAction *firstAction = [UIAlertAction actionWithTitle:#"one"
style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"You pressed button one");
}]; // 2
UIAlertAction *secondAction = [UIAlertAction actionWithTitle:#"two"
style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"You pressed button two");
}]; // 3
[alert addAction:firstAction]; // 4
[alert addAction:secondAction]; // 5
[self presentViewController:alert animated:YES completion:nil]; // 6
For Swift:
let alert = UIAlertController(title: "My Alert", message: "This is an action sheet.", preferredStyle: .Alert) // 1
let firstAction = UIAlertAction(title: "one", style: .Default) { (alert: UIAlertAction!) -> Void in
NSLog("You pressed button one")
} // 2
let secondAction = UIAlertAction(title: "two", style: .Default) { (alert: UIAlertAction!) -> Void in
NSLog("You pressed button two")
} // 3
alert.addAction(firstAction) // 4
alert.addAction(secondAction) // 5
presentViewController(alert, animated: true, completion:nil) // 6
Here are a few ways of showing Alert messages on the iPhone
please check this link for more samples and screenshots .
(XCode project with source code included)
Simple Action Sheet
OK/Cancel Action Sheet
Simple Alert
// open a alert with an OK and cancel button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"UIAlertView"
message:#"My message" delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
For debug output you could use (sometimes it happens that you can't use NSLog due to bugs that only appear when app is launched on the device and not from Xcode):
#define MY_ALERT(str) [[[UIAlertView alloc] initWithTitle:#"System Alert" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show]
Then, in your code you could do, for example:
MY_ALERT(NSStringFromCGRect(someView.frame))
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:#"Hello world" message:#"This is an alert view" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
In this way we create an object of class UIAlertView and set the title "Hello world" and the message "This is an alert view " and the title of button as ok.
For a detail answer visit this blog