UIAlertController / ActionSheet在iPad上崩溃了,如何传递发件人?

问题描述 投票:3回答:1

我想在iPhone和iPad设备上都显示ActionSheet。虽然我的代码在iPhone上正常运行,但它不适用于iPad。原因是我需要指定显示弹出窗口的位置。结果,我试图使用this answer中提出的代码。我目前遇到的问题是,我不知道如何将参数sender传递给方法。

例如,我有一个UITableViewRowAction,点击时应显示ActionSheet

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

        let rowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Action", handler:{action, indexpath in
            print("Action for element #\(indexPath.row).");
            self.displayActionSheet()
        });

        return [rowAction];
    }

在我的情况下,哪个论据是sender?我无法将rowAction传递给displayActionSheet(),因为该变量在其自己的初始值内使用。我也试图通过self.displayDeleteLicencePlateActionSheet(self.items[indexPath.row]),但结果相同 - 我总是在else表达式的guard子句中结束:

guard let button = sender as? UIView else {
            print("sender empty")
            return
}

我想在点击ActionSheet时显示UIBarButtonItem

let myButton = UIBarButtonItem(title: "FooBar", style: .Plain, target: self, action: #selector(SecondViewController.displaySecondActionSheet(_:)))

但结果相同。如何才能做到这一点?

ios swift ipad uialertview uiactionsheet
1个回答
0
投票

请参阅以下代码以解决您的问题。

TARGET_OBJECT将是您想要显示提醒的发件人。

func showAlert() {
    let alert = UIAlertController(title: "Title", message: "Message text", preferredStyle: .alert)

    let actionOK = UIAlertAction(title: "OK", style: .default) { (alertAction) in
    }
    alert.addAction(actionOK)

    if let popoverController = alert.popoverPresentationController {
        popoverController.sourceView = self.TARGET_OBJECT // TARGET_OBJECT will be your sender to show an alert from.
        popoverController.sourceRect = CGRect(x: self.TARGET_OBJECT.frame.size.width/2, y: self.TARGET_OBJECT.frame.size.height/2, width: 0, height: 0)
    }

    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}

Please check attached image it will appear as you want.

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.