UIAlertView UITextField showing black border - ios

I am creating UIAlertView with textinput, but though I clear the background and giving border colour its showing a black border.
UIAlertView *alerttorename=[[UIAlertView alloc]initWithTitle:#"Dropbox Export" message:#"Export As:" delegate:projectDetailsReference cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alerttorename.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alerttorename textFieldAtIndex:0] setText:[appDelegate.projectName stringByDeletingPathExtension]];
UITextField *textField = [alerttorename textFieldAtIndex:0];
[textField setBackgroundColor:[UIColor clearColor]];
textField.borderStyle=UITextBorderStyleRoundedRect ;
textField.layer.borderColor=[[UIColor lightGrayColor]CGColor];
textField.layer.borderWidth = 0.1f;
textField.layer.cornerRadius = 5;
textField.clipsToBounds = YES;
alerttorename.tag=233;
[alerttorename show];

Refer this example, UIAlertController :
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField)
{
textField.placeholder = NSLocalizedString(#"LoginPlaceholder", #"Login");
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField)
{
textField.placeholder = NSLocalizedString(#"PasswordPlaceholder", #"Password");
textField.secureTextEntry = YES;
}];
The values of the text field can be retrieved in the OK action handler:
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"OK", #"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
UITextField *login = alertController.textFields.firstObject;
UITextField *password = alertController.textFields.lastObject;
}];
For more info about UIAlertController, refer this link.

Use this category for UIView to display alertView in iOS > 7.0 . Here you don't need to worry about UIAlertView or UIAlertViewController.
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#interface UIView (AlertView)
+( void )showSimpleAlertWithTitle:( NSString * )title
message:( NSString * )message
cancelButtonTitle:( NSString * )cancelButtonTitle;
#end
#interface UIView (AlertView)
+( void )showSimpleAlertWithTitle:( NSString * )title
message:( NSString * )message
cancelButtonTitle:( NSString * )cancelButtonTitle
{
if(SYSTEM_VERSION_LESS_THAN(#"8"))
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
message: message
delegate: nil
cancelButtonTitle: cancelButtonTitle
otherButtonTitles: nil];
[alert show];
}
else
{
// nil titles break alert interface on iOS 8.0, so we'll be using empty strings
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? #"": title
message: message
preferredStyle: UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle
style: UIAlertActionStyleDefault
handler: nil];
[alert addAction: defaultAction];
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[rootViewController presentViewController: alert animated: YES completion: nil];
}
}
#end
Usage of this category like this:
[UIView showSimpleAlertWithTitle:#"Title here" message:#"Message here" cancelButtonTitle:#"Ok"];

Related

How allow copy/paste/cut in UIAlertView? (iOS, Objective C)

I want to allow users to copy/cut but mainly PASTE data from other apps into my app. I need to allow them to paste data in UIAlertView, when they are logging to the app. How can i make it?
This is my code:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:[NSString stringWithFormat:NSLocalizedString(#"enter_login", nil)]
delegate:self
cancelButtonTitle:#"Ok"
[alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeEmailAddress];
[[alert textFieldAtIndex:1] becomeFirstResponder];
[UserDefaultsServices resetLoginCredentials];
[UserDefaultsServices resetLoginData];
self.alertView = alert;
[alert show];
It does this:
show what my code does, I need to allow users to paste data in password TextField
You can use this answer for swift versions :
Objective C version of shared answer is :
- (IBAction)showAlert:(id)sender {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Add New Name" message:#"Your message" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = #"Name";
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = #"Password";
textField.secureTextEntry = true;
}];
UIAlertAction *saveAction = [UIAlertAction actionWithTitle:#"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// here you can access your textfields' texts
NSString *textField1 = alertController.textFields[0].text;
NSString *textField2 = alertController.textFields[1].text;
NSLog(#"Saving %# %#", textField1, textField2);
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// here you can access your textfields' texts
NSString *textField1 = alertController.textFields[0].text;
NSString *textField2 = alertController.textFields[1].text;
NSLog(#"Canceled %# %#", textField1, textField2);
}];
[alertController addAction:saveAction];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
}
Above code work like this :

Default text in UIAlertVIew on show

It appears that there are a number of questions asking this but nothing I have tried works for me. Simply, I would like an UIAlertView with UIAlertViewStylePlainTextInput but with the input box preloaded with a given string when it is displayed - not as a placeholder, but as a default entry. Is this possible?
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"message" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[[alert textFieldAtIndex:0] setText:[NSString stringWithFormat:#"%#", #"preloaded string"]];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
The example above uses setText which does not work. I have also tried:
[[alert textFieldAtIndex:0] setPlaceholder:#"text"];
just for interest, but this does not display even the placeholder so maybe I am missing something else.
Any pointers?
Use UIAlertController instead:
let alertController = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
// Configure UITextField here...
textField.placeholder = "Placeholder"
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (_) -> Void in
let textField = alertController.textFields![0] as UITextField
let value = textField.text ?? "Untitled"
/// Save value here...
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
you can do it like
AlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"sample" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done", nil];
[alert setAlertViewStyle: UIAlertViewStylePlainTextInput];
// Alert style customization
[[alert textFieldAtIndex:0] setDelegate:self];
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[[alert textFieldAtIndex:0] setText:#"Richard"];
[[alert textFieldAtIndex:0] setPlaceholder:#"textvalue"];
[alert show];
UIAlertController
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:#"sample"
message:#" "
preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField)
{
[textField setText:#"Richard"];
textField.placeholder = NSLocalizedString(#"textvalue", #"Login");
}];
[alert addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// do your action on ok click
}]];
[alert addAction:[UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// do your action on cancel click
}]];
UIViewController *viewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
if ( viewController.presentedViewController && !viewController.presentedViewController.isBeingDismissed ) {
viewController = viewController.presentedViewController;
}
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:alert.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:viewController.view.frame.size.height*2.0f];
[alert.view addConstraint:constraint];
[viewController presentViewController:alert animated:YES completion:^{
}];
it is working 100%
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"message" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setText:[NSString stringWithFormat:#"%#", #"preloaded string"]];
[alert show];
you either need to create your own custom "popup" view that will look like UIAlertviewlike in here or use a open source implementation like SDCAlertView
what you can also do is to use UIAlertController (as UIAlertview is also deprecated in IOS 8)
UITextField *alert = alertController.textFields.firstObject;
[alert setText#"YOUR ALERT TEXT HERE"];

UIAlertView first deprecated IOS 9

I have tried several ways to use UIAlertController,instead of UIAlertView. I tried several ways but I cannot make the alert action work.
Here is my code that works fine in IOS 8 and IOS 9 but is showing up with deprecated flags. I tried the elegant suggestion below but I can't make it function in this context. I need to submit my app and this is the last thing to address. Thank You for any further suggestions. I am a newbie.
#pragma mark - BUTTONS ================================
- (IBAction)showModesAction:(id)sender {
NSLog(#"iapMade: %d", iapMade3);
// IAP MADE ! ===========================================
if (!iapMade3) {
//start game here
gamePlaysCount++;
[[NSUserDefaults standardUserDefaults]setInteger:gamePlaysCount forKey:#"gamePlaysCount"];
NSLog(#"playsCount: %ld", (long)gamePlaysCount);
if (gamePlaysCount >= 4) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE
delegate:self
cancelButtonTitle:#"Yes, please"
otherButtonTitles:#"No, thanks", nil];
[alert show];
NSString *path = [[NSBundle mainBundle] pathForResource:#"cow" ofType:#"wav"];
_pop =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[_pop play];
[self dismissViewControllerAnimated:true completion:nil];
} else {
if (gamePlaysCount == 1) {
// Create & store the next 5 mins when player gets 3 more lives
nextDateToPlay = [[NSDate date] dateByAddingTimeInterval:60*60*0.1];
NSLog(#"CURRENT DATE: %#", [NSDate date]);
NSLog(#"NEXT DAY: %#", nextDateToPlay);
[[NSUserDefaults standardUserDefaults]setObject: nextDateToPlay forKey:#"nextDateToPlay"];
NSLog(#"nextDateToPlay: %#", nextDateToPlay);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE2
delegate:self
cancelButtonTitle:#"Got it!"
otherButtonTitles:#"Start", nil];
[alert show];
} else {
if (gamePlaysCount == 3) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Basic"
message: THREE_PLAYS_LIMIT_MESSAGE3
delegate:self
cancelButtonTitle:#"Yep, I Know!"
otherButtonTitles:#"Start", nil];
[alert show];
}
}
}
}
}
// IAP NOT MADE =============================
#pragma mark - ALERTVIEW DELEGATE ============================
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:#"Yes, please"]) {
UIStoryboard *storyboard = self.storyboard;
MenuViewController *svc = [storyboard instantiateViewControllerWithIdentifier:#"Store"];
svc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:svc animated:YES completion:nil];
}
}
From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:
UIAlertView is deprecated. Use UIAlertController with a preferredStyle
of UIAlertControllerStyleAlert instead
So you should use something like this
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];
//Calling
[self showMessage:#"There is no internet connection for this device"
withTitle:#"Error"];
//Method
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
If you want to use this alert in NSObject class you should use like:
-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
}];
});
}
Swift version of new implementation is :
let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
Xcode 8 + Swift
Assuming self is a UIViewController:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
Make UIAlertController+AlertController Category as:
UIAlertController+AlertController.h
typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);
#interface UIAlertController (AlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock;
#end
UIAlertController+AlertController.m
#implementation UIAlertController (NTAlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock {
UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
if(cancelButtonTitle != nil) {
UIAlertAction *cancelButton = [UIAlertAction
actionWithTitle:cancelButtonTitle
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
}];
[alertController addAction:cancelButton];
}
if(otherButtonTitle != nil) {
UIAlertAction *otherButton = [UIAlertAction
actionWithTitle:otherButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
}];
[alertController addAction:otherButton];
}
[controller presentViewController:alertController animated:YES completion:nil];
return alertController;
}
#end
in your ViewController.m
[UIAlertController showAlertIn:self WithTitle:#"" message:#"" cancelButtonTitle:#"Cancel" otherButtonTitles:#"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){
if(index == ALERTACTION_CANCEL){
// CANCEL BUTTON ACTION
}else
if(index == ALERTACTION_OTHER){
// OTHER BUTTON ACTION
}
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
NOTE: If you want to add more than two buttons then add another
more UIAlertAction to the UIAlertController.
Use UIAlertController instead of UIAlertView
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
I tried the above methods, and no one can show the alert view, only when I put the presentViewController: method in a dispatch_async sentence:
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alert animated:YES completion:nil];
});
Refer to Alternative to UIAlertView for iOS 9?.
-(void)showAlert{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self showAlert]; // calling Method
Check this:
UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:#"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *camera =[UIAlertAction actionWithTitle:#"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self Action]; //call Action need to perform
}];
[alertctrl addAction:camera];
-(void)Action
{
}
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Are you sure you want to logout?"
message:#""
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Logout"
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction * action)
{
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:noButton];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];

iOS 8: UIAlertView / UIAlertController not showing text or buttons

I have an UIAlertView which is getting shown perfectly in iOS 7 but in iOS 8, it does not show any buttons or labels. Alert is still visible but just a small white box.
The OK and cancel buttons take their events as well but no texts are visible.
I have used this alert to show on click of a button
- (IBAction)sel_btnLogout:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Logout!" message:#"Are you sure you want to logout?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
}
I checked the frame in iOS 8: it is giving (0,0,0,0) but in iOS 7 it is giving a definite value.
I also checked for iterating into the subviews of uialertview. In iOS7, it goes in the loop, as it finds alert's subviews. In iOS8, it says there are no subviews of alertView.
Check if the class is available
if ([UIAlertController class])
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Alert title" message:#"Alert message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
else
{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:#"Alert title" message:#"Alert message" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
With iOS 8 you can set the title instead of the message:
[[[UIAlertView alloc] initWithTitle:#"AlertView in iOS 8." message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
UIAlertView is deprecated from iOS 8 for more information visit this
http://nshipster.com/uialertcontroller/.
https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UIAlertViewDelegate_Protocol/index.html
So if you're going to write separate code for iOS 7 and iOS 8, you should be using UIAlertController instead:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"AlertView in iOS 8" message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}]];
[self presentViewController:alertController animated:YES completion:nil];
I got the answer to my issue. The issue was that I was using UIFont+Replacement category in my project. This was working fine on iOS 7 but on iOS 8 it was using few deprecated methods. Due to this, I don't know why, but only my alert view was not showing any labels.
Solution: Deleted the category from the project and set font through xib. Once we place the .tff file of any font in our project workspace, we see those font names in the xib under custom fonts. NO NEED TO USE UIFont+Replacement category.
Please read through the code below to understand how to add the fields and buttons to the alerts.
- (IBAction)UIAlertControllerWithActionSheetTextFields:(id)sender {
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Info"
message:#"You are using UIAlertController with Actionsheet and text fields"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"Resolving UIAlert Action for tapping OK Button");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"Resolving UIAlertActionController for tapping cancel button");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.accessibilityIdentifier = #"usernameTextField";
textField.placeholder = #"Enter your username";
textField.accessibilityLabel = #"usernameLabel";
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = #"Enter your password";
textField.accessibilityIdentifier = #"paswordTextField";
textField.accessibilityLabel = #"passwordLabel";
}];
[self presentViewController:alert animated:YES completion:nil];
}
and if you need a project to completely refer the types of Alerts that are available in IOS, please follow my project from the below URL:
Alert variations in IOS
in iOS 8 you need to replace UIAletrview and UIActionSheet with UIAlertcontroller . You read first This documentation in apple forum
Apple Alertcontroller
You can check that code
if (([[[UIDevice currentDevice] systemVersion] compare:#"8.0" options:NSNumericSearch] == NSOrderedAscending))
{
// use UIAlertView
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:Title message:desc delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else {
// use UIAlertController
UIAlertController *alert = [UIAlertController alertControllerWithTitle:Title message:desc preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
let alert = UIAlertController(title: "Warning" as String , message: messageString as String, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.dismissViewControllerAnimated(true, completion: nil)
}
// Add the actions
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
i think this is not UIAlertview Issues.
please check this work fine..
i think your code issues...........
in any view controller put this code in viewDidLoad Like below:
- (void)viewDidLoad
{
[super viewDidLoad];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"My message" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
}

Adding a simple UIAlertView

What is some starter code I could use to make a simple UIAlertView with one "OK" button on it?
When you want the alert to show, do this:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ROFL"
message:#"Dee dee doo doo."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// If you're not using ARC, you will need to release the alert view.
// [alert release];
If you want to do something when the button is clicked, implement this delegate method:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// the user clicked OK
if (buttonIndex == 0) {
// do something here...
}
}
And make sure your delegate conforms to UIAlertViewDelegate protocol:
#interface YourViewController : UIViewController <UIAlertViewDelegate>
Other answers already provide information for iOS 7 and older, however UIAlertView is deprecated in iOS 8.
In iOS 8+ you should use UIAlertController. It is a replacement for both UIAlertView and UIActionSheet. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.
To create a simple Alert View you can do the following:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
Swift 3 / 4 / 5:
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:
NSString *alertTitle = #"Title";
NSString *alertMessage = #"Message";
NSString *alertOkButtonText = #"Ok";
if (#available(iOS 8, *)) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:alertOkButtonText, nil];
[alertView show];
}
else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
Swift 3 / 4 / 5:
let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"
if #available(iOS 8, *) {
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: alertOkButtonText,
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
}
else {
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
alertView.show()
}
UPD: updated for Swift 5. Replaced outdated class presence check with availability check in Obj-C.
UIAlertView is deprecated on iOS 8. Therefore, to create an alert on iOS 8 and above, it is recommended to use UIAlertController:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
// Enter code here
}];
[alert addAction:defaultAction];
// Present action where needed
[self presentViewController:alert animated:YES completion:nil];
This is how I have implemented it.
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Title"
message:#"Message"
delegate:nil //or self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert autorelease];
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Title"
message:#"Message"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok",nil];
[myAlert show];
As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.
Here is a complete method that only has one button, an 'ok', to close the UIAlert:
- (void) myAlert: (NSString*)errorMessage
{
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:errorMessage
message:#""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"ok", nil];
myAlert.cancelButtonIndex = -1;
[myAlert setTag:1000];
[myAlert show];
}
This page shows how to add an UIAlertController if you are using Swift.
Simple alert with array data:
NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:#"Name"];
NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:#"message"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name
message:msg
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];

Resources