Ответ 1
Ознакомьтесь с примером UICatalog на веб-сайте Apple. В разделе "Предупреждения" приведены примеры использования команды UIActionSheet для выполнения того, что вы пытаетесь сделать.
Я хотел бы создать всплывающее меню, подобное тому, которое было найдено в почтовом приложении, когда вы хотите ответить на сообщение. Я видел это в более чем одном приложении, поэтому я не был уверен, что в нем есть что-то встроенное в него или какой-то пример кода.
Ознакомьтесь с примером UICatalog на веб-сайте Apple. В разделе "Предупреждения" приведены примеры использования команды UIActionSheet для выполнения того, что вы пытаетесь сделать.
Код был протестирован с Swift 5
Начиная с iOS 8, используется UIAlertController
сочетании с UIAlertControllerStyle.ActionSheet
. UIActionSheet
устарела.
Вот код для создания листа действий на изображении выше:
class ViewController: UIViewController {
@IBOutlet weak var showActionSheetButton: UIButton!
@IBAction func showActionSheetButtonTapped(sender: UIButton) {
// Create the action sheet
let myActionSheet = UIAlertController(title: "Color", message: "What color would you like?", preferredStyle: UIAlertController.Style.actionSheet)
// blue action button
let blueAction = UIAlertAction(title: "Blue", style: UIAlertAction.Style.default) { (action) in
print("Blue action button tapped")
}
// red action button
let redAction = UIAlertAction(title: "Red", style: UIAlertAction.Style.default) { (action) in
print("Red action button tapped")
}
// yellow action button
let yellowAction = UIAlertAction(title: "Yellow", style: UIAlertAction.Style.default) { (action) in
print("Yellow action button tapped")
}
// cancel action button
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (action) in
print("Cancel action button tapped")
}
// add action buttons to action sheet
myActionSheet.addAction(blueAction)
myActionSheet.addAction(redAction)
myActionSheet.addAction(yellowAction)
myActionSheet.addAction(cancelAction)
// present the action sheet
self.present(myActionSheet, animated: true, completion: nil)
}
}
Все еще нужна помощь? Посмотрите это видео урок. Вот как я это узнал.
UIAlertController
действий UIAlertController
а не UIActionSheet
.)Это UIAlertController
на iOS 8+ и UIActionSheet
в более ранних версиях.
Вам нужно использовать таблицу UIActionSheet.
Сначала вам нужно добавить UIActionSheetDelegate в ваш файл ViewController.h.
Затем вы можете ссылаться на таблицу действий с помощью:
UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Select Sharing option:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
@"Share on Facebook",
@"Share on Twitter",
@"Share via E-mail",
@"Save to Camera Roll",
@"Rate this App",
nil];
popup.tag = 1;
[popup showInView:self.view];
Затем вы должны обрабатывать каждый из вызовов.
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (popup.tag) {
case 1: {
switch (buttonIndex) {
case 0:
[self FBShare];
break;
case 1:
[self TwitterShare];
break;
case 2:
[self emailContent];
break;
case 3:
[self saveContent];
break;
case 4:
[self rateAppYes];
break;
default:
break;
}
break;
}
default:
break;
}
}
Это было устаревшим с iOS 8.x.
Так вы можете сделать это в Objective-C на iOS 8 +:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Directions"
message:@"Select mode of transportation:"
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *drivingAction = [UIAlertAction actionWithTitle:@"Driving" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// this block runs when the driving option is selected
}];
UIAlertAction *walkingAction = [UIAlertAction actionWithTitle:@"Walking" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// this block runs when the walking option is selected
}];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:drivingAction];
[alert addAction:walkingAction];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
Для всех, кто ищет решение в Swift:
Принять UIActionSheetDelegate
протокол
Создайте и покажите ActinSheet:
let sheet: UIActionSheet = UIActionSheet()
sheet.addButtonWithTitle("button 1")
sheet.addButtonWithTitle("button 2")
sheet.addButtonWithTitle("button 3")
sheet.addButtonWithTitle("Cancel")
sheet.cancelButtonIndex = sheet.numberOfButtons - 1
sheet.delegate = self
sheet.showInView(self.view)
Функция делегата:
func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 0:
NSLog("button1");
case 1:
NSLog("button2");
case 2:
NSLog("button3");
case actionSheet.cancelButtonIndex:
NSLog("cancel");
break;
default:
NSLog("blub");
break;
}
}
Я попытался добавить ActionSheet в свое представление. Поэтому я пытался найти идеальное решение, но некоторые ответы смутили меня. Потому что большинство вопросов о листе действий были написаны так давно. Также он не обновлялся. В любом случае... Я напишу старую версию ActionSheet и обновленную версию ActionSheet. Надеюсь, мой ответ способен сделать ваш мозг мирным.
---------- Обновленная версия ---------
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Action Sheet" message:@"writeMessageOrsetAsNil" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* actionSheet01 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) { NSLog(@"OK click");}];
UIAlertAction* actionSheet02 = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {NSLog(@"OK click");}];
UIAlertAction* actionSheet03 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
NSLog(@"Cancel click");}];
[browserAlertController addAction:actionSheet01];
[browserAlertController addAction:actionSheet02];
[browserAlertController addAction:actionSheet03];
[self presentViewController:browserAlertController animated:YES completion:nil];
------- Старая версия ------
UIActionSheet *actionSheet= [[UIActionSheet alloc] initWithTitle:@"Select Sharing option:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"OK", @"NO",@"Cancel",
nil];
actionSheet.tag = 100;
[actionSheet showInView:self.view];
- (void)actionSheet:(UIActionSheet *)actionShee clickedButtonAtIndex:(NSInteger)buttonIndex {
if( actionSheet.tag == 100){
switch (buttonIndex) {
case 0:
[self doSomething];
break;
case 1:
[self doAnything];
break;
case 2:
[self doNothing];
break;
default:
break;
}
break;
}
}