UIPopover Как сделать всплывающее окно с такими кнопками?

введите здесь описание изображения

Мне интересно, как я могу создать всплывающее окно с такими кнопками.

ОТВЕЧАТЬ:

UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: nil 
                                                          delegate: self
                                                 cancelButtonTitle: nil 
                                            destructiveButtonTitle: nil 
                                                 otherButtonTitles: @"Take Photo",
                                                                    @"Choose Existing Photo", nil];

[actionSheet showFromRect: button.frame inView: button.superview animated: YES];

Где-то еще в вашем классе делегированных объектов...

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
         // take photo...
    } 
    else if (buttonIndex == 1) {
         // choose existing photo...
    }
}

person ManOx    schedule 24.05.2012    source источник


Ответы (2)


Это UIActionSheet. На iPhone он анимируется снизу. На iPad он отображается во всплывающем окне.

Предполагая, что вы делаете это нажатием кнопки:

UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: nil 
                                                          delegate: self
                                                 cancelButtonTitle: nil 
                                            destructiveButtonTitle: nil 
                                                 otherButtonTitles: @"Take Photo",
                                                                    @"Choose Existing Photo", nil];

[actionSheet showFromRect: button.frame inView: button.superview animated: YES];

В iOS8+ вы должны использовать новый класс UIAlertController:

UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                          message: nil
                                                                   preferredStyle: UIAlertControllerStyleActionSheet];
[alertController addAction: [UIAlertAction actionWithTitle: @"Take Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    // Handle Take Photo here
}]];
[alertController addAction: [UIAlertAction actionWithTitle: @"Choose Existing Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    // Handle Choose Existing Photo here
}]];

alertController.modalPresentationStyle = UIModalPresentationPopover;

UIPopoverPresentationController * popover = alertController.popoverPresentationController;
popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
popover.sourceView = sender;
popover.sourceRect = sender.bounds;

[self presentViewController: alertController animated: YES completion: nil];

или в Swift

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertController.addAction(UIAlertAction(title: "Take Photo", style: .Default, handler: { alertAction in
    // Handle Take Photo here
    }))
alertController.addAction(UIAlertAction(title: "Choose Existing Photo", style: .Default, handler: { alertAction in
    // Handle Choose Existing Photo
    }))
alertController.modalPresentationStyle = .Popover

let popover = alertController.popoverPresentationController!
popover.permittedArrowDirections = .Up
popover.sourceView = sender
popover.sourceRect = sender.bounds

presentViewController(alertController, animated: true, completion: nil)
person Ashley Mills    schedule 24.05.2012
comment
Мне просто добавить это в представление Popover? - person ManOx; 25.05.2012
comment
Нет, просто используйте один из методов showFrom... UIActionSheet. Смотрите мой обновленный ответ для примера - person Ashley Mills; 25.05.2012
comment
Хорошо и еще 1 вопрос, как настроить обработчики событий на кнопки? - person ManOx; 25.05.2012
comment
Можно ли поместить новую кнопку общего доступа Facebook в UIAlertController или мне нужно написать всплывающее окно для клиента? Я попробовал второй подход, так как Storyboard, похоже, задыхается от всплывающих окон, связанных с конкретным UITableViewCell, и не будет компилироваться. - person PhillipOReilly; 19.09.2015

Подобно другим ответам, но это очень легко реализовать в сравнении.

Заставьте свой класс использовать UIActionSheetDelegate.

Пример:

@interface ExampleViewController : UIViewController <UIActionSheetDelegate>

Затем добавьте в свой ExampleViewController.mm/m

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex  { //Get the name of the current pressed button 
NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex]; 
if  ([buttonTitle isEqualToString:@"Remove"]) {
    NSLog(@"Remove this actionSheet"); } 
if ([buttonTitle isEqualToString:@"Button 1"]) {
    NSLog(@"Button 1 pressed"); } 
if ([buttonTitle isEqualToString:@"Button 2"]) {
    NSLog(@"Button 2 pressed"); }
if ([buttonTitle isEqualToString:@"Button 3"]) {
    NSLog(@"Button 3 pressed"); } 
if ([buttonTitle isEqualToString:@"Cancel"]) {
    NSLog(@"Cancel clicked (anywhere away from it)"); } }

Теперь в событии нажатия кнопки или где/когда вы хотите, чтобы всплывающее окно вызывало следующее:

    - (IBAction)aButtonPressed:(id)sender {
     NSString *actionSheetTitle = @"Action Sheet"; // Title 
     NSString *destroyTitle = @"Destroy"; // Button titles
     NSString *button1 = @"Button 1"; 
     NSString *button2 = @"Button 2";
     NSString *button3 = @"Button 3";
     NSString *cancelTitle = @"Cancel"; 
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:actionSheetTitle
                                   delegate:self
                                   cancelButtonTitle:cancelTitle
                                   destructiveButtonTitle:destroyTitle
                                   otherButtonTitles:button1, button2, button3, nil]; [actionSheet showInView:self.view];
}

И дополнительная информация об этом @: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIActionSheet_Class/Reference/Reference.html

person Danoli3    schedule 23.04.2013
comment
Не забудьте добавить [actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view анимированный:YES]; чтобы прикрепить всплывающее окно к кнопке отправителя. - person Matt Privman; 24.12.2014