4
2

More than 3 years have passed since last update.

UIBarButtonItemのSystemItemで使えるUIImageを取得する

Last updated at Posted at 2020-08-12

経緯

アプリからTwitterやメモアプリ等の外部アプリに画像など、情報を共有したい時のボタンにアクションボタンを使用したい場合がある
↓こういうやつ
IMG_7856.PNG
こういう場合に限らず、画像の横にある本の画像、またはゴミ箱画像とかも使いたい。
UIBarButtonItemだと使えるけど、それからUIImageを引き出す事は基本的にできない…
それに画像をネットから同じような画像を探すにしても、商用利用などを確認するのも面倒すぎる…🤦‍♂️

という事で、UIBarButtonItemのSystemItemからimageだけを使用する方法を共有します💁‍♂️

実装

検証環境は下記の通りです
OS:10.15.6
Xcode:11.6
Swift:5.0

早速ですが、実装したコードの紹介をします

UIBarButtonItem.SystemItem+extention.swift
extension UIBarButtonItem.SystemItem {
    func image() -> UIImage? {
        let tempItem = UIBarButtonItem(barButtonSystemItem: self,
                                       target: nil,
                                       action: nil)

        let bar = UIToolbar()
        bar.setItems([tempItem],
                     animated: false)
        bar.snapshotView(afterScreenUpdates: true)

        // imageを取得する
        let itemView = tempItem.value(forKey: "view") as! UIView
        for view in itemView.subviews {
            if let button = view as? UIButton,
                let image = button.imageView?.image {
                return image.withRenderingMode(.alwaysTemplate)
            }
        }
        return nil
    }
}

使う時はこのように↓

UIBarButtonItem.SystemItem.action.image()

実行結果↓
スクリーンショット 2020-08-12 11.24.04.png
問題なく表示できました〜!☺️

候補: SF Symbol・systemNameを検討する

そもそも論ですが、iOS13からはSF SymbolUIImageViewでsystemNameが使用できるようになっています。
使用する方法は以下の通りです。

// UIKit
UIImageView(systemName: "xxx")

// SwiftUI
Image(systemname: "xxx")

この"xxx"に入る文字列は、下記URLよりDLできるSF Symbolアプリから確認できます。
https://developer.apple.com/design/resources/
FigamaやSketch等のデザインツールを利用すると細かくサイズ等を調整したりできるみたいなので
対応できる方はこっちの方がいいと思います。
※記事投稿時点ではBeta版です

最後に

Twitterのアカウントがありますのでフォローしてくれると嬉しいです!!
@swift_nita
なお今回のサンプルはGithubに上げていますのでご参考までに!
https://github.com/ni-ta/ButtonItemSystemItem

参考

Use UIBarButtonItem icon in UIButton
SF Symbolsの使い方とカスタマイズの仕方

4
2
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
4
2