UIActivityViewController示例项目
用两个按钮设置故事板,并将它们连接到视图控制器(参见下面的代码).
将图像添加到Assets.xcsets.我把我的叫作"狮子".
密码
import UIKit
class ViewController: UIViewController {
// share text
@IBAction func shareTextButton(_ sender: UIButton) {
// text to share
let text = "This is some text that I want to share."
// set up activity view controller
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToFacebook ]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
// share image
@IBAction func shareImageButton(_ sender: UIButton) {
// image to share
let image = UIImage(named: "Image")
// set up activity view controller
let imageToShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToFacebook ]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
}
结果
单击"共享一些文本"在左侧显示结果,单击"共享图像"在右侧显示结果.
注意事项
- 我用iOS11和Swift 4重新测试了这一点.我不得不在模拟器中运行了几次才能正常工作,因为它超时了.这可能是因为我的电脑太慢了.
- 如果您希望隐藏其中的一些选项,可以使用
excludedActivityTypes
来实现,如上面的代码所示.
- 不包括
popoverPresentationController?.sourceView
行会导致你的应用程序在iPad上运行时崩溃.
- 这不允许您将文本或图像共享到其他应用程序.你可能要
UIDocumentInteractionController
英镑才能买到.
另请参阅