UIAlertController/ActionSheet在iPad上崩溃,如何传递发送者?

3
我想在iPhone和iPad设备上显示一个"ActionSheet"。尽管我的代码在iPhone上正常工作,但在iPad上却不行。原因是我需要指定一个位置来显示弹出窗口。因此,我尝试使用这个答案中提供的代码。目前遇到的问题是,我不知道如何将参数"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]),但结果相同-我总是最终进入guard表达式的else子句:

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

当单击UIBarButtonItem时,我还希望显示一个ActionSheet

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

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

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)
}

请查看附加的图片,它会呈现出您想要的样子。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接