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
Related
I have a very simple process running where after each round of a simple game the scores are calculated, labels updated and all the normal, very simple stuff. I have a UIAlertView that informs the player of how s/he performed. I use a UIAlertViewDelegate to postpone all the updates, resetting of controls etc. till after the UIAlertView is dismissed. The methods are [startNewRound],[startOver] and [updateLabels]. It's fairly obvious what they all do. Anyway, when the user hits round ten, I've made another UIAlertView that informs the player that the game has ended and shows the overall score. Again, I hoped to use a delegate to postpone the resets till after the AlertView is dismissed. The only problem is, with the endGame AlertView, it seems to be using the first AlertView's delegate method causing the game to continue with a new round and not start from the beginning. I hope this makes sense. Anyway, here are snippets of my code.
if (round == 10){
UIAlertView *endGame = [[UIAlertView alloc]
initWithTitle: #"End of Game"
message: endMessage
delegate:self
cancelButtonTitle:#"New Game"
otherButtonTitles:nil];
[endGame show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: title
message: message
delegate:self
cancelButtonTitle:#"Next"
otherButtonTitles:nil];
[alertView show];
}
And then the delegate methods:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self startNewRound];
[self updateLabels];
}
- (void)endGame:(UIAlertView *)endGame didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self startOver];
}
So there it is. As I mentioned, the endGame AlertView appears to be using alertView's delegate, thus not activating the [self startOver] method. All the methods are working, it's just the AlertView is using the incorrect delegate method. Regards, Mike
Change your code like this,
if (round == 10){
UIAlertView *endGame = [[UIAlertView alloc]
initWithTitle: #"End of Game"
message: endMessage
delegate:self
cancelButtonTitle:#"New Game"
otherButtonTitles:nil];
endGame.tag = 111;
[endGame show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: title
message: message
delegate:self
cancelButtonTitle:#"Next"
otherButtonTitles:nil];
alertView.tag = 222;
[alertView show];
}
and delegate method as,
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 111)
{
[self startNewRound];
[self updateLabels];
}
else if(alertView.tag == 222)
{
[self startOver];
}
}
You cant have two delegate method for dismisswithbuttonindex, you need to handle this situation with tag.
Give both alert view a different tag and check it on delegate object. Thus you can differentiat the both alert view.
Hello and good afternoon, I'm having some issues here, and to be honest, I don't understand
I have to create different alertViews for the same screen with different messages, most of these alerts only have 1 button, but there's this one to delete that needs 2 buttons, the thing is that, since the others have only 1 button, when I created the 2 button screenview and I added the (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex method, I have some problems
some code here
- (IBAction)saveInfo{
if (med.text.length ==0) {
UIAlertView *alertViewError = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"ERROR",#"")
message:NSLocalizedString(#"EMPTY1",#"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertViewError show];
[alertViewError release];
}
else if(medicamento.text.length >= 41){
[self lenghtError:40:NSLocalizedString(#"TF_MED",#"")];
}
else if (med.text.length ==0 || descripcion.text.length == 0) {
UIAlertView *alertViewError = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"ERROR",#"")
message:NSLocalizedString(#"EMPTY2",#"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertViewError show];
[alertViewError release];
}
else if (descripcion.text.length >= 41){
[self lenghtError:40:NSLocalizedString(#"TF_DESCRIPCION",#"")];
}
else{
[self insertDictionary];
UIAlertView *alertViewAcept = [[UIAlertView alloc] initWithTitle:#""
message: NSLocalizedString(#"ACCEPT_MSG",#"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertViewAcept show];
[alertViewAcept release];
[self.navigationController popViewControllerAnimated:YES];
}
}
- (IBAction)cancelData{
UIAlertView *alertViewCancel =
[[UIAlertView alloc] initWithTitle: NSLocalizedString(#"BT_DELETE_MED",#"")
message: NSLocalizedString(#"MSG_DELETE_MED",#"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: #"Cancel", nil];
[alertViewCancel setTag:999];
[alertViewCancel show];
[alertViewCancel release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 999) {
if(buttonIndex==0){
[self.Bayer_DB_obj deleteRowWithKeyValue:[NSString stringWithFormat:#"%d",IdMed] onKeyName:#"id_ctl_med" onTable:#"ctl_med"];
// code to delete here
[self.navigationController popViewControllerAnimated:YES];
}
}
}
So, in the first part, I created some alerts to indicate the user that he/she is making a mistake, in the second part, I need a confirmation before deletion, but here, I need 2 buttons, then, in the 3rd part, I have the method that is been called, I added a tag to my alert to avoid doing this comparison in all the alerts, the problem is that, when you show alertViewAcept, it takes you to the previous view controller, and after you click the ok button (that actually is the cancelbuttontitle) the app crashes without any "error message"
so I'm not sure what I'm doing wrong, please help
My guess the problem is that you set the delegate for the alertViewAcept, and right after you showed the alert, you pop the viewController and so your delegate will get released, which will then give you an error once a button on the alert view is clicked.
You should do this:
UIAlertView *alertViewAcept = [[UIAlertView alloc] initWithTitle:#""
message: NSLocalizedString(#"ACCEPT_MSG",#"")
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
Even better, all your alerts which only have the OK button, do not need a delegate. And in that case you do not even need the tag.
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.
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)
I have some three xib files, a b c
there is a button on b,and it will show an alert when click it,the code is
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Warning"
message:#"You will jump to a when you click 'Yes,Go',or click 'No,I am not' for exit"
delegate:nil
cancelButtonTitle:#"Yes,Go"
cancelButtonTitle:#"No,I am not"
otherButtonTitles:nil];
[alert show];
[alert release];
as its description, I want to jump to the a when I click the 'Yes,Go',this app will be closed if I click 'No,I am not'
So what should do?
Thanks
you can handle the event in alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
here check for button index and do what you want.
First of write your UIAlertView like below,
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"You will jump to a when you click 'Yes,Go',or click 'No,I am not' for exit"
delegate:self
cancelButtonTitle:#"Yes,Go"
otherButtonTitles:#"No,I am not"
,nil];
[alert show];
[alert release];
then you can handle which button is tapped by user as below code:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex ==0)
{
//handle it for "Yes,Go"
}
else if (buttonIndex ==1)
{
//handle it for "No,I am not"
}
}
We are missing a lot of details here to answer this question I think. What is the structure of your program? How do you show the xib files etc.