【问题标题】:Sharing button works perfectly on iPhone but crash on iPad共享按钮在 iPhone 上完美运行,但在 iPad 上崩溃
【发布时间】:2015-10-08 23:03:41
【问题描述】:

我正在尝试添加一个按钮,以便在 Twitter、Facebook 等中分享一些句子。它适用于所有 iPhone 型号,但模拟器在 iPad 上崩溃。

这是我的代码:

@IBAction func shareButton(sender: AnyObject) {

    frase = labelFrases.text!
    autor = labelAutores.text!


    var myShare = "\(frase) - \(autor)"

    let activityVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)



    self.presentViewController(activityVC, animated: true, completion: nil)

这是错误:

由于未捕获的异常“NSGenericException”而终止应用程序,原因:“UIPopoverPresentationController (<_uialertcontrolleractionsheetregularpresentationcontroller:>) 应该在演示发生之前设置一个非零的 sourceView 或 barButtonItem

我该如何解决?谢谢

【问题讨论】:

    标签: swift share social


    【解决方案1】:

    对于 ipad (iOS > 8.0) 你需要设置 popoverPresentationController:

        //check ipad
        if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
        {
            //ios > 8.0
            if ( activityVC.respondsToSelector(Selector("popoverPresentationController")) ) {
                activityVC.popoverPresentationController?.sourceView = super.view
            }
        }
    
        self.presentViewController(activityVC, animated: true, completion: nil)
    

    更多信息在这里: UIActivityViewController crashing on iOS8 iPads

    【讨论】:

      【解决方案2】:

      Swift 5 执行此操作,以使共享按钮在 iPad 和 iPhone 上都可以使用:

         @IBAction func shareButton(sender: UIButton) { {
          let itemToShare = ["Some Text goes here"]
          let avc = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)
      
          //Apps to be excluded sharing to
          avc.excludedActivityTypes = [
              UIActivityType.print,
              UIActivityType.addToReadingList
          ]
          // Check if user is on iPad and present popover
          if UIDevice.current.userInterfaceIdiom == .pad {
              if avc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
                  avc.popoverPresentationController?.barButtonItem = sender
              }
          }
          // Present share activityView on regular iPhone
          self.present(avc, animated: true, completion: nil)
      }
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多