In the previous chapter I have shown you how to show Alerts using UIAlertController. UIAlertCntroller is not only used to show alertviews. It is used to create action sheets also. Now we can see how the same UIAlertController can be used to create actionsheets.
When we're showing alerts, the preferredStyle parameter should be UIAlertControllerStyleAlert. For creating actionsheets all you need to do is just changing it to UIAlertControllerStyleActionSheet.
The following is the code snippet to create actionsheet. This example has a Label called _lblWelcome and Its background color is changed when different buttons on the actionsheet is tapped.
Note that the destructive style (UIAlertActionStyleDestructive ) buttons will have text in Red and cancel style (UIAlertActionStyleCancel) action buttons are shown separately as shown in the figure below. UIAlertActionStyleDefault buttons are normal action buttons which has text in Blue.
+ (instancetype)alertControllerWithTitle:(NSString *)title
message:(NSString *)message
preferredStyle:(UIAlertControllerStyle)preferredStyle;
When we're showing alerts, the preferredStyle parameter should be UIAlertControllerStyleAlert. For creating actionsheets all you need to do is just changing it to UIAlertControllerStyleActionSheet.
The following is the code snippet to create actionsheet. This example has a Label called _lblWelcome and Its background color is changed when different buttons on the actionsheet is tapped.
UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[actionSheet addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
// do nothing.
}]];
[actionSheet addAction:[UIAlertAction actionWithTitle:@"Green" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// Do action when Green button is tapped
_lblWelcome.backgroundColor = UIColor.greenColor;
}]];
[actionSheet addAction:[UIAlertAction actionWithTitle:@"Yellow" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// Do action when Yellow button is tapped
_lblWelcome.backgroundColor = UIColor.yellowColor;
}]];
[actionSheet addAction:[UIAlertAction actionWithTitle:@"Red" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
// Do action when Destructive button Red is tapped
_lblWelcome.backgroundColor = UIColor.redColor;
}]];
[self presentViewController:actionSheet animated:YES completion:nil];
Note that the destructive style (UIAlertActionStyleDestructive ) buttons will have text in Red and cancel style (UIAlertActionStyleCancel) action buttons are shown separately as shown in the figure below. UIAlertActionStyleDefault buttons are normal action buttons which has text in Blue.