【问题标题】:UIAlertController/ActionSheet crashes on iPad, how to pass sender?UIAlertController/ActionSheet 在 iPad 上崩溃,如何传递发件人?
【发布时间】:2016-08-09 09:33:43
【问题描述】:

我想在 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]),但结果相同——我总是在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(_:)))

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

【问题讨论】:

    标签: ios swift ipad uialertview uiactionsheet


    【解决方案1】:

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

    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.

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 2017-02-20
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多