Adding a simple UIAlertView - ios

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];

Related

can someone help me to fix this error

UIAlertController *alert = [[UIAlertController alloc] initWithTitle: alertString message:nil
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
I'm having this error:
No visible #interface for 'UIAlertController' declares the selector 'show'
and this : No visible #interface for 'UIAlertController' declares the selector 'initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:'
This true of step to declare UIAlertController
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
// add action button
UIAlertAction *okAction = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:okAction]; // add action button to alert controller
// present alert controller in view
[self presentViewController:alertController animated:YES completion:nil];

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 compatible for iOS 7, 8, or later [duplicate]

I am using Swift to write an app and I need to show an alert. The app must be iOS 7 and iOS 8 compatible. Since UIAlertView has been replaced with UIAlertController, how can I check if the UIAlertController is available without checking the system version? I have been hearing that Apple recommends that we should not check the system version of the device in order to determine the availability of an API.
This is what I am using for iOS 8 but this crashes on iOS 7 with "dyld: Symbol not found: _OBJC_CLASS_$_UIAlertAction" :
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
If I use the UIAlertView for iOS 8, I get this warning: Warning: Attempt to dismiss from view controller <_UIAlertShimPresentingViewController: 0x7bf72d60> while a presentation or dismiss is in progress!
The detection pattern is identical to the Objective-C style.
You need to detect whether the current active runtime has the ability to instantiate this class
if objc_getClass("UIAlertController") != nil {
println("UIAlertController can be instantiated")
//make and use a UIAlertController
}
else {
println("UIAlertController can NOT be instantiated")
//make and use a UIAlertView
}
Don't try and work out this based on the OS version. You need to detect abilities NOT OS.
EDIT
The original detector for this answer NSClassFromString("UIAlertController") fails under -O optimisation so its been changed to the current version which does work for Release builds
EDIT 2
NSClassFromString is working at all optimisations in Xcode 6.3/Swift 1.2
For non-swift code, pure objective-C do this
if ([UIAlertController class])
{
// use UIAlertController
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:#"Enter Folder Name"
message:#"Keep it short and sweet"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
//Do Some action here
UITextField *textField = alert.textFields[0];
NSLog(#"text was %#", textField.text);
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
NSLog(#"cancel btn");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"folder name";
textField.keyboardType = UIKeyboardTypeDefault;
}];
[self presentViewController:alert animated:YES completion:nil];
}
else
{
// use UIAlertView
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Enter Folder Name"
message:#"Keep it short and sweet"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
dialog.alertViewStyle = UIAlertViewStylePlainTextInput;
dialog.tag = 400;
[dialog show];
}
I was annoyed that I kept having to write out both situations, so I wrote a compatible UIAlertController that works for iOS 7 as well so I just threw it up on GitHub. I did my best to replicate the (much better) methods of adding buttons and actions of the UIAlertController. Works with both Objective-C and Swift. I'm posting this as I found this question when searching on Google and figured it could be helpful for others.
https://github.com/BayPhillips/compatible-alert-controller
You can resolve your issue using this code :-
var device : UIDevice = UIDevice.currentDevice()!;
var systemVersion = device.systemVersion;
var iosVerion : Float = systemVersion.bridgeToObjectiveC().floatValue;
if(iosVerion < 8.0) {
let alert = UIAlertView()
alert.title = "Noop"
alert.message = "Nothing to verify"
alert.addButtonWithTitle("Click")
alert.show()
}else{
var alert : UIAlertController = UIAlertController(title: "Noop", message: "Nothing to verify", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style:.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
and UIKit had to be marked Optional rather than Required.
Courtsey :- Alert that can work on iOS 7 and iOS 8
Swift 2.0
if #available(iOS 8.0, *) {
} else {
}
If this is shared code, and there is the possibility that the code can be used in an iOS 8 extension (where UIAlertView and UIActionSheet are restricted APIs) as well as iOS 7, where UIAlertController does not exist, have a look at: JVAlertController
It is an API-compatible back-port of UIAlertController to iOS 7, that I undertook to make SDK code safe for use in both iOS 7 and iOS 8 extensions.
You could use a category to solve that (though you'll need to convert it to Swift):
#implementation UIView( AlertCompatibility )
+( void )showSimpleAlertWithTitle:( NSString * )title
message:( NSString * )message
cancelButtonTitle:( NSString * )cancelButtonTitle
{
if( [[UIDevice currentDevice] isSystemVersionLowerThan: #"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
#implementation UIDevice( SystemVersion )
-( BOOL )isSystemVersionLowerThan:( NSString * )versionToCompareWith
{
if( versionToCompareWith.length == 0 )
return NO;
NSString *deviceSystemVersion = [self systemVersion];
NSArray *systemVersionComponents = [deviceSystemVersion componentsSeparatedByString: #"."];
uint16_t deviceMajor = 0;
uint16_t deviceMinor = 0;
uint16_t deviceBugfix = 0;
NSUInteger nDeviceComponents = systemVersionComponents.count;
if( nDeviceComponents > 0 )
deviceMajor = [( NSString * )systemVersionComponents[0] intValue];
if( nDeviceComponents > 1 )
deviceMinor = [( NSString * )systemVersionComponents[1] intValue];
if( nDeviceComponents > 2 )
deviceBugfix = [( NSString * )systemVersionComponents[2] intValue];
NSArray *versionToCompareWithComponents = [versionToCompareWith componentsSeparatedByString: #"."];
uint16_t versionToCompareWithMajor = 0;
uint16_t versionToCompareWithMinor = 0;
uint16_t versionToCompareWithBugfix = 0;
NSUInteger nVersionToCompareWithComponents = versionToCompareWithComponents.count;
if( nVersionToCompareWithComponents > 0 )
versionToCompareWithMajor = [( NSString * )versionToCompareWithComponents[0] intValue];
if( nVersionToCompareWithComponents > 1 )
versionToCompareWithMinor = [( NSString * )versionToCompareWithComponents[1] intValue];
if( nVersionToCompareWithComponents > 2 )
versionToCompareWithBugfix = [( NSString * )versionToCompareWithComponents[2] intValue];
return ( deviceMajor < versionToCompareWithMajor )
|| (( deviceMajor == versionToCompareWithMajor ) && ( deviceMinor < versionToCompareWithMinor ))
|| (( deviceMajor == versionToCompareWithMajor ) && ( deviceMinor == versionToCompareWithMinor ) && ( deviceBugfix < versionToCompareWithBugfix ));
}
#end
Then just call
[UIView showSimpleAlertWithTitle: #"Error" message: message cancelButtonTitle: #"OK"];
But, if you do not want to check the system version, just use
BOOL lowerThaniOS8 = NSClassFromString( #"UIAlertController" ) == nil;
inside the category UIView( AlertCompatibility )
If your using both iOS 7- UIAlertView and iOS 8+ UIAlertController as described above, and you want your UIAlertController blocks to call your UIAlertView's delegate (e.g. MyController) alertView:didDismissWithButtonIndex method to continue processing the results, here is an example of how to do that:
if ([UIAlertController class]) {
MyController * __weak mySelf = self;
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:alertCancel
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
[mySelf alertView:nil didDismissWithButtonIndex:0];
}
];
...
This uses Apple's recommendation for capturing self in a block: Avoid Strong Reference Cycles when Capturing self
Of course, this method assumes you only have one UIAlertView in the controller and therefore pass nil as its value to the delegate method. Otherwise, you'd need to instantiate (and tag) a "fake" UIAlertView to pass to alertView:didDismissWithButtonIndex.
Here to check two way of UIAlertView and UIAlertContoller.
Check 1 : iOS verstion check UIAlertController Class.
if #available(iOS 8.0, *) {
// UIALertController
let alert = UIAlertController(title: "Alert", message: "Alert after 8.0", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
} else {
// UIALertView
UIAlertView(title: "Alert", message: "Alert below iOS V 8.0", delegate: nil, cancelButtonTitle: "OK").show()
}
Check 2 : check UIAlertController nil then iOS version below 8.0.
if objc_getClass("UIAlertController") != nil {
// UIALertController
let alert = UIAlertController(title: "Alert", message: "Alert after 8.0", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
else {
// UIALertView
UIAlertView(title: "Alert", message: "Alert below iOS V 8.0", delegate: nil, cancelButtonTitle: "OK").show()
}
If you want to be compatible with iOS 7, just don't use UIAlertController. Simple as that.
UIAlertView has not been replaced, it still works perfectly and will continue to work perfectly for the foreseeable future.
Here is my drag and drop swift solution:
//Alerts change in iOS8, this method is to cover iOS7 devices
func CozAlert(title: String, message: String, action: String, sender: UIViewController){
if respondsToSelector("UIAlertController"){
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: action, style: UIAlertActionStyle.Default, handler:nil))
sender.presentViewController(alert, animated: true, completion: nil)
}
else {
var alert = UIAlertView(title: title, message: message, delegate: sender, cancelButtonTitle:action)
alert.show()
}
}
Call like this:
CozAlert("reportTitle", message: "reportText", action: "reportButton", sender: self)
Beware this is only for the most basic alerts, you might need additional code for advanced stuff.
Try below code. It works fine for both iOS 8 and below version.
if (IS_OS_8_OR_LATER) {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
}];
[alertVC addAction:cancelAction];
[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:alertVC animated:YES completion:^{
}];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
download alert class from this link
and use it easily for ios 6 ,7 and 8
//Old code
**UIAlertView** *alert=[[**UIAlertView** alloc]initWithTitle:#"FreeWare" message:#"Welcome to Common class" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
//New code
**MyAlertView** *alert=[[**MyAlertView** alloc]initWithTitle:#"FreeWare" message:#"Welcome to Common class" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
In iOS8, there is a new class UIAlertController that replaces UIAlertView and UIActionSheet. From iOS8 on, use UIAlertController, and for iOS8 and before use UIAlertView and UIActionSheet. I think that iOS8 added size classes that change UIAlertView display direction. See: https://github.com/wangyangcc/FYAlertManage

Use of undeclared identifier 'alert'

I am getting an error that says: Use of undeclared identifier 'alert'
NSAlert *alert = [NSAlert alertWithMessageText: #"Why ? "
defaultButton:#"OK"
];
Can someone tell me why am i getting this error ?
Updated:
I think you mean
UIAlertView *alert
Not
NSAlert *alert // "NSAlert" does not exist in the Cocoa API.
Your clue from the compiler is that it says the type NSAlert is undefined. If the type is undefined, then you can get another error about the variable itself being undefined, which is why it says alert is undefined.
For iOS, you need UIAlertView, not NSAlert. NSAlert is a Mac OS X class.
Refer
Where is NSAlert.h in the iOS SDK?
For OS 8 & above use UIAlertController & for below use UIAlertview.
if(SYSTEM_VERSION_LESS_THAN(#"8.0"))
{
alertView = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Please enter CVV2 code." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
txt_CVV2CodeResult.text = #"";
}
else
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Warning:" message:#"Please enter CVV2 code." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *OKAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"OK", #"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
}];
[alertController addAction:OKAction];
[self presentViewController:alertController 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];
}

Resources