Быстрый UIAlertController-> Катастрофические отказы ActionSheet iPad iOS8

в настоящее время я сталкиваюсь с большой проблемой со своим ActionSheet. На iPhone это работает отлично, но на iPad это только отказывает

Я создаю новый проект только с одной кнопкой

import UIKit

extension ViewController : UIActionSheetDelegate {

    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {

        if actionSheet.tag == 0 {
            if buttonIndex == 1 {
                // doing something for "product page"
            } else if (buttonIndex == 2) {
                // doing something for "video"
            }
        }
    }

}

class ViewController: UIViewController, UIActionSheetDelegate {
    @IBAction func test(sender: AnyObject) {

        let systemVersion: NSInteger = (UIDevice.currentDevice().systemVersion as NSString).integerValue
        if systemVersion < 8 {
            // iOS7:
            let action:UIActionSheet = UIActionSheet(title: "Change Map Type", delegate: self, cancelButtonTitle: "Back", destructiveButtonTitle: nil, otherButtonTitles: "Product Page", "Video")
            action.tag = 0
            action.showInView(self.view)
        } else {
            // iOS8:
            let alertController: UIAlertController = UIAlertController(title: "Change Map Type", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
            let cancelAction: UIAlertAction = UIAlertAction(title: "Back", style: UIAlertActionStyle.Cancel, handler: nil)
            let button1action: UIAlertAction = UIAlertAction(title: "Product Page", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> () in
                // doing something for "product page"
            })
            let button2action: UIAlertAction = UIAlertAction(title: "Video", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> () in
                // doing something for "video"
            })
            alertController.addAction(cancelAction)
            alertController.addAction(button1action)
            alertController.addAction(button2action)

            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

}

Как я сказал относительно iPhone, он работает, но если я нажимаю кнопку на iPad Сбои приложения с

25.09.2014 14:54:52.784 тестов [9541:1970048] * Завершающееся приложение из-за неперехваченного исключения 'NSGenericException', причина: 'Ваше приложение представило UIAlertController () стиля UIAlertControllerStyleActionSheet. modalPresentationStyle UIAlertController с этим стилем является UIModalPresentationPopover. Необходимо предоставить информацию о местоположении для этой легкой сдобы через popoverPresentationController аварийного контроллера. Необходимо обеспечить или sourceView и sourceRect или barButtonItem. Если эта информация не известна при представлении аварийного контроллера можно обеспечить его в методе UIPopoverPresentationControllerDelegate-prepareForPopoverPresentation'. * Сначала бросьте стек вызовов: (0 CoreFoundation 0x00613df6 exceptionPreprocess + 182 1 libobjc. A.dylib
0x01fdaa97 objc_exception_throw + 44 2 UIKit
0x0164da37 - [UIPopoverPresentationController presentationTransitionWillBegin] + 3086 3 UIKit
0x00f54f75 __ 71-[UIPresentationController _initViewHierarchyForPresentationSuperview:] _ block_invoke + 1666 4 UIKit 0x00f53554 __ 56-[UIPresentationController runTransitionForCurrentState] _block_invoke + 226 5 UIKit
0x00f8721b __ 40 + [UIViewController _scheduleTransition:] _ block_invoke + 18 6 UIKit 0x00e4d62e ___ afterCACommitHandler_block_invoke + 15 7 UIKit 0x00e4d5d9 _applyBlockToCFArrayCopiedToStack + 415 8 UIKit
0x00e4d3ee _afterCACommitHandler + 545 9 CoreFoundation
0x00536fbe __ CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION
+ 30 10 CoreFoundation 0x00536f00 __ CFRunLoopDoObservers + 400 11 CoreFoundation 0x0052c93a __ CFRunLoopRun + 1226 12 CoreFoundation 0x0052c1ab CFRunLoopRunSpecific + 443 13 CoreFoundation
0x0052bfdb CFRunLoopRunInMode + 123 14 GraphicsServices
0x0438424f GSEventRunModal + 192 15 GraphicsServices
0x0438408c GSEventRun + 104 16 UIKit
0x00e23e16 UIApplicationMain + 1526 17 тестов
0x00085e9e top_level_code + 78 18 тестов
0x00085edb, основной + 43 19 libdyld.dylib
0x0273eac9 запускаются + 1 20???
0x00000001 0x0 + 1) libc ++ abi.dylib: завершение с неперехваченным исключением типа NSException

Проект может быть найден в https://www.dropbox.com/s/54jqd8nsc67ll5g/test.zip? dl=0 для загрузки и попытки.

60
задан 15 March 2017 в 17:47

3 ответа

Если Вы хотите представить его в центре без стрелок на iPad [ Swift 3 + ]:

    if let popoverController = alertController.popoverPresentationController {
        popoverController.sourceView = self.view
        popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        popoverController.permittedArrowDirections = []
    }
    self.present(alertController, animated: true, completion: nil)
3
ответ дан 1 November 2019 в 09:33

Если кто-то использует отправитель: UITapGestureRecognizer это могло бы быть полезно.

@objc func popupSettings(sender : UITapGestureRecognizer) {
    .....
    if let popoverPresentationController = alert.popoverPresentationController {
        popoverPresentationController.sourceView = self.view
        popoverPresentationController.sourceRect = CGRect(origin: sender.location(in: self.view), size: CGSize(width: 1.0, height: 1.0))
    }
    self.present(alert, animated: true, completion: nil)
}
1
ответ дан 1 November 2019 в 09:33

Если Вы хотите, показывают Ваше предупреждение в центре и никакой стрелке, я попробовал это, это работает над iOS 11.2

быстро 4,2 версии:

let actionSheet = UIAlertController ......
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){

        if let currentPopoverpresentioncontroller = actionSheet.popoverPresentationController{
            currentPopoverpresentioncontroller.permittedArrowDirections = []
            currentPopoverpresentioncontroller.sourceRect = CGRect(x: (self.view.bounds.midX), y: (self.view.bounds.midY), width: 0, height: 0)
            currentPopoverpresentioncontroller.sourceView = self.view
            self.present(actionSheet, animated: true, completion: nil)
        }
    }else{
        self.present(actionSheet, animated: true, completion: nil)
    }

версия Objective C:

UIAlertController* actionSheet 
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    NSArray *empty;
    UIPopoverPresentationController *currentPopOverPresentationController = [actionSheet popoverPresentationController];
    currentPopOverPresentationController.permittedArrowDirections = empty;
    currentPopOverPresentationController.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds), 0, 0);
    currentPopOverPresentationController.sourceView = self.view;

    [self presentViewController:actionSheet animated:YES completion:nil];
}else{
    [self presentViewController:actionSheet animated:YES completion:nil];
}
0
ответ дан 1 November 2019 в 09:33

Другие вопросы по тегам:

Похожие вопросы: