简体   繁体   English

尝试通过点击UIBarButtonItem进行共享时,iPad崩溃

[英]iPad crashes when trying to share by taping a UIBarButtonItem

I'm developing an iOS app with Xcode and Swift. 我正在使用Xcode和Swift开发iOS应用。

I'm using this code to share a defined string by taping a UIButton : 我正在使用此代码通过点击UIButton来共享定义的字符串:

@IBAction func shareApp(sender: UIButton) {
    let textToShare = "Look at this:"

    if let myWebsite = NSURL(string: "www.example.con") {
        let objectsToShare = [textToShare, myWebsite]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

        if #available(iOS 8.0, *) {
            activityVC.popoverPresentationController?.sourceView = sender
        } else {
            // Fallback on earlier versions
        }
        self.presentViewController(activityVC, animated: true, completion: nil)
    }
}

That works very well on iPhone and iPad. 在iPhone和iPad上效果很好。

Now, I want to do the same, but using UIBarButtonItem instead of UIButton . 现在,我想做同样的事情,但是使用UIBarButtonItem而不是UIButton Of cause, This code doesn't work for UIBarButtonItem. 当然,此代码不适用于UIBarButtonItem。

Changing @IBAction func shareApp(sender: AnyObject) { and activityVC.popoverPresentationController?.sourceView = sender as? UIView 更改@IBAction func shareApp(sender: AnyObject) {activityVC.popoverPresentationController?.sourceView = sender as? UIView activityVC.popoverPresentationController?.sourceView = sender as? UIView causes a crash on iPad's as soon as I tap on the BarButtonItem. 当我点击BarButtonItem时, activityVC.popoverPresentationController?.sourceView = sender as? UIView会导致iPad's崩溃。

Does anybody know how to fix it? 有人知道如何解决吗?

For iPad in addition to source view for popoverPresentationController, you would also need to add sourceRect as well. 对于iPad,除了popoverPresentationController的源代码视图之外,您还需要添加sourceRect。 Try the following: 请尝试以下操作:

 if ( UIDevice.currentDevice().userInterfaceIdiom == .Pad) {

     if let fromView = sender as? UIView {
              youActivityVC.popoverPresentationController.sourceView = fromView

    youActivityVC.popoverPresentationController.sourceRect = fromView.frame
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM