1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】UIActivityItemをカスタムする

Last updated at Posted at 2023-03-31

環境

macOS Monterey バージョン 12.6.3
Xcode バージョン 14.2

やりたいこと

共有ボタン(Action Button)が押された時に表示されるアイコン、テキストをカスタムしたい
IMG_2623.PNG

コード

iOS13以降で利用可能なLPLinkMetadataを使って共有画面の内容をカスタムします。

内容を書き換えやすいよう、ActivityItemのカスタムクラスを作成します。

CustomShareItem.swift
class CustomShareItem: NSObject, UIActivityItemSource {
    var shareURL: URL
    var shareText: String
    var shareImage: UIImage
    
    init(shareURL: URL, shareText: String, shareImage: UIImage) {
        self.shareURL = shareURL
        self.shareText = shareText
        self.shareImage = shareImage
    }
    
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return ""
    }
    
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return nil
    }
    
    func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
        let metaData = LPLinkMetadata()
        metaData.originalURL = shareURL
        metaData.url = metaData.originalURL
        metaData.title = shareText
        metaData.imageProvider = NSItemProvider(object: shareImage)
        return metaData
    }
}
ViewController.swift
    func share() {
        let url = URL(string: "https://www.mlb.com/") ?? nil
        let text = "Sample Text"
        let image = UIImage(named: "sample") ?? nil

        let shareItem = CustomShareItem(shareURL: url!, shareText: text, shareImage: image!)
        let activityViewController = UIActivityViewController(activityItems: [shareItem, self], applicationActivities: nil)
        present(activityViewController, animated: true, completion: nil)
    }

参考

少し読み解くのが難しいですが、こちらの記事も参考にしています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?