How to use UIAlertView?

This Tutorial deals with how to use UIAlertView in your application…

Let us suppose our viewController class is myViewController and we want an alert on the press of a button

Drag a button from library to view in myViewController.xib

Now come to myViewController.h

Add the following highlighted lines of code

Now in myViewController.m

Add the implementation of “showAlert”

-(IBAction)showAlert
{
	UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Alert user" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"button1",@"button2",nil];
	[alert show];
	[alert release];
}

Also add the following delegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSLog(@"Pressed button %d",buttonIndex);
}

The above delegate method will get called everytime you press some button on UIAlertView and will tell the index number of the button pressed

In myViewController.xib make the connections as shown

Save and run application. Output is shown below

Now see how delegation method works. Suppose buttons are pressed in order   button1->Show Alert->button2->Show Alert->OK

then see the output on console

 

 

How to add a simple UIButton in a UIView by coding?


This post deals with adding a button in UIView by coding…

Create a button

 

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

button1.frame = CGRectMake(x, y, width, height);

where x and y are coordinates

width is width of the button,height is height of the button

[button1 setTitle:@"Hello" forState:UIControlStateNormal];

 

Add the button to parent view

[[self view] addSubview:button1];

How to know which UIButton was pressed?

How to know which UIButton is pressed when

there are more than one UIButton in a view?

 

Suppose there are two buttons in a view

Now in the identity inspector window for button0 set the tag value=0

Set the tag value for button1 as 1 in the same way as for button0

 

Now here is the coding part

Link the following method with both the buttons in the Interface Builder

-(IBAction)action:(id)sender
{
if ([sender tag]==0) {
NSLog(@"button0");
}
else
{
NSLog(@"button1");
}
}

Here sender gets the identity of the button object which is pressed.

By using  [sender tag] we get to know which button was pressed.

Same thing applies for more than two buttons provided different tag values should be used for each UIButton object.