XCode: Create A Simple AlertView

Open Xcode and create a new Single View Application. For product name, use SimpleAlertView and then fill out the Organization Name and Company Identifier with your customary values. Select iPhone for Devices.




Drag a button inside the view controller and change its title to "Show AlertView".



We will need to connect the button to the view controller. Select the assistant editor and open the ViewController.m file. Ctrl and drag from the label to the class section and create the following action.



Inside the ViewController.m, change the line
@interface ViewController ()
to
@interface ViewController () <UIAlertViewDelegate>


Inside the method of btn_showAlertView that we have created, insert this lines of code
 
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"OK Dialog"
message:@"This is OK dialog"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[alert addButtonWithTitle:@"Cancel"];
[alert show];




To handle which button is clicked, insert this method

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"You have clicked Ok");
}
else if(buttonIndex == 1)
{
NSLog(@"You have clicked Cancel");
}
}

Build and Run the project, an alert view should appear when the "Show AlertView" button is clicked.

You can download the source code of the SimpleAlertView at my repository on bitbucket.

0 nhận xét:

Đăng nhận xét