UIActionSheet/UIAlertController multiline text - ios

This is the code I am writing to display UIActionSheet.
actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(#"updateresponseforrecurring", nil) delegate:self cancelButtonTitle:NSLocalizedString(#"Cancel", nil) destructiveButtonTitle:nil otherButtonTitles:
NSLocalizedString(#"updateresponseonlyforthis", nil),
NSLocalizedString(#"updateresponseforallactivities", nil),
nil];
actionSheet.tag = 2;
[actionSheet showInView:[UIApplication sharedApplication].keyWindow];
This is what I get using this :
Clearly, second option is longer and thus the size gets smaller to accommodate the width.
But I want the same font size for all the options which leaves me with multiline. Also tried with UIAlertController but not able to set multiline text.
How to achieve this ?

This seems to work in iOS 10 and Swift 3.1:
UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).numberOfLines = 2

This is not possible with the standard UIAlertController or UIAlertView.
I would recommend you to make it shorter. Why don't you make an alert and type something like this:
Do you want to update the response only for this instance or for all
activities in this series.
The answers would be these:
Only this instance
All activities

In iOS 10:
If you want to apply it to all UIAlertController, you can use these lines of code:
[[UILabel appearanceWhenContainedIn:[UIAlertController class], nil] setNumberOfLines:2];
[[UILabel appearanceWhenContainedIn:[UIAlertController class], nil] setFont:[UIFont systemFontOfSize:9.0]];
put this in didFinishLaunchingWithOptions method of the AppDelegate.

try this
let alert = UIAlertController(title: title,
message: "you message go here",
preferredStyle:
UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
UILabel.appearance(whenContainedInInstancesOf:
[UIAlertController.self]).numberOfLines = 0
UILabel.appearance(whenContainedInInstancesOf:
[UIAlertController.self]).lineBreakMode = .byWordWrapping

Related

How to change UIAlertController button text colour in iOS9?

The question is similar to iOS 8 UIActivityViewController and UIAlertController button text color uses window's tintColor but in iOS 9.
I have a UIAlertController and the dismiss button keeps white colour even I have tried to set
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor blackColor]];
UIAlertController *strongController = [UIAlertController alertControllerWithTitle:title
message:message
preferredStyle:preferredStyle];
strongController.view.tintColor = [UIColor black];
I've run into something similar in the past and the issue seems to stem from the fact that the alert controller's view isn't ready to accept tintColor changes before it's presented. Alternatively, try setting the tint color AFTER you present your alert controller:
[self presentViewController:strongController animated:YES completion:nil];
strongController.view.tintColor = [UIColor black];
In Swift 3.x:
I found the following to work effectively. I call this at app launch .
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = UIColor.black
So this would change the tint color of all UIAlertViewController button labels in your app globally. The only button label color it doesn't change are those which have a UIAlertActionStyle of destructive.
Objective-C
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Title text" message:#"Message text" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
//code here…
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Later" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
//code here….
}];
[ok setValue:[UIColor greenColor] forKey:#"titleTextColor"];
[cancel setValue:[UIColor redColor] forKey:#"titleTextColor"];
[alertController addAction:ok];
[alertController addAction:cancel];
[alertController.view setTintColor:[UIColor yellowColor]];
[self presentViewController:alertController animated:YES completion:nil];
Swift 3
let alertController = UIAlertController(title: "Title text", message: "Message text", preferredStyle: .alert)
let ok = UIAlertAction(title: "Yes" , style: .default) { (_ action) in
//code here…
}
let cancel = UIAlertAction(title: "Later" , style: .default) { (_ action) in
//code here…
}
ok.setValue(UIColor.green, forKey: "titleTextColor")
cancel.setValue(UIColor.red, forKey: "titleTextColor")
alertController.addAction(ok)
alertController.addAction(cancel)
alertController.view.tintColor = .yellow
self.present(alertController, animated: true, completion: nil)
I was able to solve this by subclassing UIAlertController:
class MyUIAlertController: UIAlertController {
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
//set this to whatever color you like...
self.view.tintColor = UIColor.blackColor()
}
}
This survives a device rotation while the alert is showing.
You also don't need to set the tintColor after presenting the alert when using this subclass.
Though it isn't necessary on iOS 8.4, this code does work on iOS 8.4 as well.
Objective-C implementation should be something like this:
#interface MyUIAlertController : UIAlertController
#end
#implementation MyUIAlertController
-(void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
//set this to whatever color you like...
self.view.tintColor = [UIColor blackColor];
}
#end
After alot of research, I found out how to make this work:
let cancelButton = UIAlertAction(title: button, style: UIAlertAction.Style.cancel, handler: { (action) in alert.dismiss(animated: true, completion: nil)
})
cancelButton.setValue(UIColor.systemBlue, forKey: "titleTextColor")
alert.addAction(cancelButton)
Just change the UIColor.systemBlue to what ever color you want, and it will make just that button a special color. I made this example (I created 3 UIAlertActions to make it.):
With just UIAlertAction.Style.whatever, it can only make it blue or red. If you change the UIColor, it will make it any color you want!
swift3
Tried to use UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = MyColor but this prevents other items unrelated to the UIAlertController from tintColor configuration. I saw it while trying to change the color of navigation bar button items.
I switched to an extension (based on Mike Taverne's response above) and it works great.
extension UIAlertController {
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
//set this to whatever color you like...
self.view.tintColor = MyColor
}
}
You can change it using: Swift 3.x
strongController.view.tintColor = UIColor.green
There is a problem with setting the tint color on the view after presenting; even if you do it in the completion block of presentViewController:animated:completion:, it causes a flicker effect on the color of the button titles. This is sloppy, unprofessional and completely unacceptable.
The one sure-fire way to solve this problem and to do it everywhere, is via adding a category to UIAlertController and swizzling the viewWillAppear.
The header:
//
// UIAlertController+iOS9TintFix.h
//
// Created by Flor, Daniel J on 11/2/15.
//
#import <UIKit/UIKit.h>
#interface UIAlertController (iOS9TintFix)
+ (void)tintFix;
- (void)swizzledViewWillAppear:(BOOL)animated;
#end
The implementation:
//
// UIAlertController+iOS9TintFix.m
//
// Created by Flor, Daniel J on 11/2/15.
//
#import "UIAlertController+iOS9TintFix.h"
#import <objc/runtime.h>
#implementation UIAlertController (iOS9TintFix)
+ (void)tintFix {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method method = class_getInstanceMethod(self, #selector(viewWillAppear:));
Method swizzle = class_getInstanceMethod(self, #selector(swizzledViewWillAppear:));
method_exchangeImplementations(method, swizzle);});
}
- (void)swizzledViewWillAppear:(BOOL)animated {
[self swizzledViewWillAppear:animated];
for (UIView *view in self.view.subviews) {
if (view.tintColor == self.view.tintColor) {
//only do those that match the main view, so we don't strip the red-tint from destructive buttons.
self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
[view setNeedsDisplay];
}
}
}
#end
Add a .pch (precompiled header) to your project and include the category:
#import "UIAlertController+iOS9TintFix.h"
Make sure you register your pch in the project properly, and it will include the category methods in every class that uses the UIAlertController.
Then, in your app delegates didFinishLaunchingWithOptions method, import your category and call
[UIAlertController tintFix];
and it will automatically propagate to every single instance of UIAlertController within your app, whether launched by your code or anyone else's.
This solution works for both iOS 8.X and iOS 9.X and lacks the flicker of the tint change post-presentation approach.
Mad props to Brandon above for starting this journey, unfortunately my reputation was not sufficient enough to comment on his post, or else I would have left it there!
[[UIView appearance] setTintColor:[UIColor black]];
this will change all the UIView tintColor as well as UIAlertController's view
The most reasonable way is set the main window's tintColor. As a uniform appearance is what we usually need.
// in app delegate
window.tintColor = ...
Other solutions have defects
Use apperance
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = ...
Not works on iOS 9, tests with iOS 11 SDK.
[[UIView appearance] setTintColor:[UIColor black]];
Are you serious?
Set UIAlertController view's tintColor is unstable. The color may change when user press the button or after view layout.
Subclass UIAlertController and overwrite layout method is hack way which is unacceptable.
I found a solution to this. Not an elegant solution, but a solution.
I swizzled viewWillAppear: on UIAlertController, then looped through the views and modified the tint color. In my case I had a tintColor set on the entire window and despite setting the tintColor via appearance the UIAlertController maintained the color on the window. I check if the color is equal to that of the window and if so apply a new one. Blindly applying the tintColor to all views will result in the red tint on destructive actions to be reset.
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method swizzleMethod = class_getInstanceMethod(self, #selector(viewWillAppear:));
Method method = class_getInstanceMethod(self, #selector(alertSwizzle_viewWillAppear:));
method_exchangeImplementations(method, swizzleMethod);
});
}
- (void)alertSwizzle_viewWillAppear:(BOOL)animated
{
[self alertSwizzle_viewWillAppear:animated];
[self applyTintToView:self.view];
}
- (void)applyTintToView:(UIView *)view
{
UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;
for (UIView *v in view.subviews) {
if ([v.tintColor isEqual:mainWindow.tintColor]) {
v.tintColor = [UIColor greenColor];
}
[self applyTintToView:v];
}
}
However this doesn't work on iOS 8, so you'll still need to set the apperance tint color.
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor greenColor]];
In Swift 2.2 you can use following code
// LogOut or Cancel
let logOutActionSheet: UIAlertController = UIAlertController(title: "Hello Mohsin!", message: "Are you sure you want to logout?", preferredStyle: .Alert)
self.presentViewController(logOutActionSheet, animated: true, completion: nil)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
print("Cancel Tapped")
}
logOutActionSheet.addAction(cancelActionButton)
let logOutActionButton: UIAlertAction = UIAlertAction(title: "Clear All", style: .Default)
{ action -> Void in
//Clear All Method
print("Logout Tapped")
}
logOutActionButton.setValue(UIColor.redColor(), forKey: "titleTextColor")
logOutActionSheet.addAction(logOutActionButton)
I wanted to make the delete button to appear red, so I used .destructive style:
alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler:{(UIAlertAction) in
You have 3 styles for the action buttons:
let style : UIAlertActionStyle = .default
// default, cancel (bold) or destructive (red)
let alertCtrl = UIAlertController(....)
alertCtrl.addAction( UIAlertAction(title: "click me", style: style, handler: {
_ in doWhatever()
}))

How to present AlertController 2 seconds after click a button

I want to present an alert view after the user click on a button at 2s. The function is to start calibration, and I want to show the user that calibration is done after 2s.
I'm counting in an array that when it reaches 20 (presents 2s), and I used
if showCalibDone {
let calibDoneAlert = UIAlertController(title: "", message: "Calibration is finished", preferredStyle: .Alert)
calibDoneAlert.addAction(UIAlertAction(title: "", style: .Default, handler: {(action: UIAlertAction!) in
self.x0 = self.average40(self.xCalibrate)
self.presentViewController(calibDoneAlert, animated: true, completion: nil)
}))
This is the counting. xCalibrate is an array which will add an object each time the accelerometer updates.
if xCalibrate.count == 40 {
println("40 achieved")
self.showCalibDone = true
}
But the alert view never appears with this if condition. I tried to put it in viewWillAppear or viewDidLoad, but it seems both are not correct.
How can I get this 'loop' be executed? Where should I put it? Or maybe I should use a timer to count?
If you just want some code to be executed after some a delay, use dispatch_after:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue()) {
// ...
}
You can also use performSelector to achieve the same results
- (void) showAlert
{
[[[UIAlertView alloc] initWithTitle:#"Title" message:#"Some message" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK",nil] show];
}
//
[self performSelector:#selector(showAlert) withObject:nil afterDelay:2.0f];

Is it possible to edit UIAlertAction title font size and style?

Now that iOS8 deprecated UIActionsheet and UIAlertview the customization working on iOS7 is not taking effect anymore. So far the only customization I'm aware is the tint color. And what I need is changing the title's font size and style which I haven't found any way of doing so with the new UIAlertAction.
Already referred to this but I'm still hoping there's a way to change at least the title size and font.
Providing you some of my code for UIAlertAction
UIAlertController * alertActionSheetController = [UIAlertController alertControllerWithTitle:#"Settings"
message:#""
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction * aboutTheAppAction = [UIAlertAction actionWithTitle:#"About the App"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
NSLog(#"About the app");
[self openAbout];
}];
[alertActionSheetController addAction:aboutTheAppAction];
[self presentViewController:alertActionSheetController animated:YES completion:nil];
You can change UIAlertAction's Font and color.
First you need to add UILabel Category
#interface UILabel (FontAppearance)
#property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR;
#end
#implementation UILabel (FontAppearance)
-(void)setAppearanceFont:(UIFont *)font {
if (font)
[self setFont:font];
}
-(UIFont *)appearanceFont {
return self.font;
}
#end
Category File is also Uploaded on following URL
https://www.dropbox.com/s/em91fh00fv3ut4h/Archive.zip?dl=0
After importing That file You need to call following function.
UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil];
[appearanceLabel setAppearanceFont:yourDesireFont]];
Above code is tested on Color and font. and that will only valid for iOS8 or greater.
It is possible to change alert action's font using private APIs. It may get you app rejected, I have not yet tried to submit such code.
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let action = UIAlertAction(title: "Some title", style: .Default, handler: nil)let attributedText = NSMutableAttributedString(string: "Some title")
let range = NSRange(location: 0, length: attributedText.length)
attributedText.addAttribute(NSKernAttributeName, value: 1.5, range: range)
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "ProximaNova-Semibold", size: 20.0)!, range: range)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
// this has to be set after presenting the alert, otherwise the internal property __representer is nil
guard let label = action.valueForKey("__representer")?.valueForKey("label") as? UILabel else { return }
label.attributedText = attributedText

How to add textfield to an alert view? Xcode 4.5 iOS6

How do I add a textfield to the alertview? I'm trying to do an app where before the app commits the editing, the user must authenticate 1st by typing his/her password on the said alertview but how can I do this? It seems like the code I've searched doesn't work anymore. Here it is:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In" message:#"Please enter your Password" delegate:self cancelButtonTitle:#"Log In" otherButtonTitles:#"Cancel", nil];
[alert addTextFieldWithValue:#"" label:#"Password"];
UITextField *tf = [alert textFieldAtIndex:0];
tf.clearButtonMode = UITextFieldViewModeWhileEditing;
tf.keyboardType = UIKeyboardTypeAlphabet;
tf.keyboardAppearance = UIKeyboardAppearanceAlert;
tf.autocapitalizationType = UITextAutocapitalizationTypeWords;
tf.autocapitalizationType = UITextAutocorrectionTypeNo;
the error said
"No visible #interface for 'UIAlertView'
declares the selector 'addTextFieldWithValue:label:'"
on the [alert addTextFieldWithValue:#"" label:#"Password"];
I also would like to ask how can I put codes on the Confirm button on the alertview.
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
or if you need it to be secure (for passwords)
alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
Edit:
I'm not 100% sure what you mean by "put codes on the confirm button" but if you want to know whether they pushed confirm or cancel, you only need to implement
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//check the button index and do something if it's the right one.
}
Adding a textField into an alert view (Swift):
let pincodeAlert:UIAlertController = UIAlertController(title: "Hello", message: "Enter a new passcode", preferredStyle: UIAlertControllerStyle.Alert)
pincodeAlert.addTextFieldWithConfigurationHandler({ (pinCodeTextField:UITextField!) -> Void in
pinCodeTextField.placeholder = "password"
pinCodeTextField.secureTextEntry = true
})
//Add the textField
pincodeAlert.addTextFieldWithConfigurationHandler({ (pinCodeTextField2:UITextField!) -> Void in
pinCodeTextField2.placeholder = "Confirm password"
pinCodeTextField2.secureTextEntry = true
})
pincodeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
//check entered passcodes
}))
pincodeAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
presentViewController(pincodeAlert, animated: true, completion: nil)
To check the data in the checkBoxes just add this in your "OK" Action handler:
let passcodeEntered:String = (pincodeAlert.textFields?.first as UITextField).text

How to implement a pop-up dialog box in iOS?

After a calculation, I want to display a pop up or alert box conveying a message to the user. Does anyone know where I can find more information about this?
Yup, a UIAlertView is probably what you're looking for. Here's an example:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No network connection"
message:#"You must be connected to the internet to use this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
If you want to do something more fancy, say display a custom UI in your UIAlertView, you can subclass UIAlertView and put in custom UI components in the init method. If you want to respond to a button press after a UIAlertView appears, you can set the delegate above and implement the - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex method.
You might also want to look at the UIActionSheet.
Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.
Alert (show me an example)
Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController.
It is worth quoting the documentation's warning and advice about creating unnecessary alerts.
Notes:
See also Alert Views, but starting in iOS 8 UIAlertView was deprecated. You should use UIAlertController to create alerts now.
iOS Fundamentals: UIAlertView and UIAlertController (tutorial)
Action Sheet (show me an example)
Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController is used to make an action sheet. Before iOS 8, UIActionSheet was used, but now the documentation says:
Important: UIActionSheet is deprecated in iOS 8. (Note that UIActionSheetDelegate is also deprecated.) To create and manage action sheets in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet.
Modal View (show me an example)
A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController with one of the Modal Presentation Styles.
See also
Presenting View Controllers from Other View Controllers
Modal Contexts
Popover (show me an example)
A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController. (Before iOS 8, UIPopoverController was the recommended method.)
In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).
See also
View Controllers: Popovers
Notifications
Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.
See also
Local and Remote Notification Programming Guide
Simple, interactive notifications in iOS 8
A note about Android Toasts
In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.
People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:
Make your own with a subclassed UIView
Import a third party project that mimics a Toast
Use a buttonless Alert with a timer
However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.
Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.
Here is a sample of how it looks in Swift 5:
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default) { (sender: UIAlertAction) -> Void in
// ... Maybe handle "OK!" being tapped.
}
alert.addAction(alertAction)
// Show.
present(alert, animated: true) { () -> Void in
// ... Maybe do something once showing is complete.
}
As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!
For older Swift version:
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:#"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
For Swift 3 & Swift 4 :
Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3
let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
//Do whatever you want here
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
Deprecated :
This is the swift version inspired by the checked response :
Display AlertView :
let alert = UIAlertView(title: "No network connection",
message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
alert.delegate = self
alert.show()
Add the delegate to your view controller :
class AgendaViewController: UIViewController, UIAlertViewDelegate
When user click on button, this code will be executed :
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
}
Although I already wrote an overview of different kinds of popups, most people just need an Alert.
How to implement a popup dialog box
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
My fuller answer is here.
Here is C# version in Xamarin.iOS
var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

Resources