【问题标题】:UIActivity activityViewController crash on iPad in SwiftSwift 中 iPad 上的 UIActivity activityViewController 崩溃
【发布时间】:2015-04-29 19:52:49
【问题描述】:

我有下面的代码来切换 UIActivityViewController

@IBAction func shareButtonClicked(sender: UIButton)
{
    let textToShare = "Text"

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

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

但它在 iPad 上崩溃了。如何在 Swift 中以模态方式呈现它?

【问题讨论】:

    标签: ios ipad swift uipopovercontroller uiactivityviewcontroller


    【解决方案1】:

    它会崩溃,因为在 iPad 中您不能像在 iPhone 中那样显示UIActivityViewController

    您需要按照 Apple 建议的设计指南将其显示在弹出框中。

    下面的代码将演示如何在UIPopoverPresentationController 中显示它。

    @IBAction func shareButtonClicked(sender: UIButton)
    {
        let textToShare = "Text"
    
        if let myWebsite = NSURL(string: "http://www.example.com/")
        {
            let objectsToShare = [textToShare, myWebsite]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    
            var nav = UINavigationController(rootViewController: activityVC)
            nav.modalPresentationStyle = UIModalPresentationStyle.Popover
            var popover = nav.popoverPresentationController as UIPopoverPresentationController!
            activityVC.preferredContentSize = CGSizeMake(500,600)
            popover.sourceView = self.view
            popover.sourceRect = CGRectMake(100,100,0,0)
    
            self.presentViewController(nav, animated: true, completion: nil)
    
        }
    }
    

    注意:使用 UIPopoverPresentationController 委托扩展您的视图控制器。

    例如:

    class MyViewController : UIViewController, UIPopoverPresentationControllerDelegate {
    //........
    }
    

    【讨论】:

    • 我在popover.delegate = self 行中遇到错误,说明“/Users/Palash/Documents/xcode/Learn the Basics/Learn the Basics/ViewController.swift:51:28: Type 'ViewController '不符合协议'UIPopoverPresentationControllerDelegate'"
    • 是的,因为您必须使用UIPopoverPresentationControllerDelegate 扩展您的视图控制器,就像我刚刚在答案末尾解释的那样。将UIPopoverPresentationControllerDelegate 添加到您的视图控制器将解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多