swift 共享按钮在iPhone上工作完美,但在iPad上崩溃

iezvtpos  于 2022-12-10  发布在  Swift
关注(0)|答案(3)|浏览(149)

我试图添加一个按钮,以便在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”,正在终止应用程序,原因:'UI弹出演示控制器(〈_UI警报控制器操作表常规演示控制器:0x7c0f9190〉)应在显示之前设置非空的sourceView或barButtonItem
我该怎么解决呢?

qeeaahzv

qeeaahzv1#

对于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 iOS 8 iPads

but5z9lq

but5z9lq2#

请改为执行以下操作,以便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)
}

希望这对你有帮助!

nhn9ugyo

nhn9ugyo3#

稍微修改版本,使其工作在任何按钮,iPad和iPhone。
Xcode 13.4.1(快速移动5.6)

let itemToShare = ["Some Text goes here"]
    let avc = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)
    
    //Apps to be excluded sharing to
    avc.excludedActivityTypes = [
        UIActivity.ActivityType.print,
        UIActivity.ActivityType.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?.sourceView = sender as? UIView
        }
    }
    // Present share activityView on regular iPhone
    self.present(avc, animated: true, completion: nil)

相关问题