LoginSignup
0
1

More than 1 year has passed since last update.

スクリーンショットをとってSNSにシェアするアプリ機能を実装してみた[iOSアプリ]

Last updated at Posted at 2021-05-15

今回は、スクリーンショットをとってSNSにシェアできる機能を作ってみたので、アウトプットしようと思います。

環境

・Mac Book Pro(macOS:BigSur)
・Xcode(ver:12.5)

実装例

Unknown.gif

コード例

ViewController.swift
class ViewController: UIViewController {

    @IBOutlet weak var screenShotConfirm: UIImageView!
    var screenShotImage:UIImage!
    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func takeScreenShot(_ sender: Any) {

        let width = CGFloat(UIScreen.main.bounds.width)
        let height = CGFloat(UIScreen.main.bounds.height / 1.3)
        let size = CGSize(width:width,height:height)

        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        "viewに書き出す"
        self.view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        screenShotImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

       showToast()

    }
    @IBAction func share(_ sender: Any) {
        let item = [screenShotImage!] as [Any]
        let activityVC = UIActivityViewController(activityItems: item, applicationActivities: nil)

        present(activityVC, animated: true, completion: nil)
    }

    "トースト表示を作成"
    func showToast(){
        let toastLabel = UILabel()
        toastLabel.frame = CGRect(x:40, y: UIScreen.main.bounds.height - 58, width: 300, height: 40)
        toastLabel.text = "スクリーンショットを撮りました。"
        toastLabel.layer.borderWidth = 1.0
        toastLabel.textAlignment = .center
        toastLabel.layer.borderColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        toastLabel.layer.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        toastLabel.layer.cornerRadius = 10
        toastLabel.textColor = .white
        self.view.addSubview(toastLabel)

        UIView.animate(withDuration: 2.5){
            toastLabel.alpha = 0.0
        }

        return
    }
}

スクリーンショッを撮影するボタンを押しただけでは、取れたかがわからないので撮影が終わったよの合図を
するためにトースト表示を作りました。

ネットの情報を見る限りでは、スクリーンショットのコードの書き方は、決まっているようでした。
これからのアプリ作成で使うことがあるかもしれないので、備忘録として記事を作りました。

0
1
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
0
1