![見出し画像](https://assets.st-note.com/production/uploads/images/98080284/rectangle_large_type_2_ac9b99bcb789d714d2543fb73bbcbc57.png?width=800)
iOSの ImageViewer による画像ビューアの作成
iOSの「ImageViewer」による画像ビューアの作成を試したので、まとめました。
・Xcode 14
・iOS 16
1. ImageViewer
「ImageViewer」は、iOSで画像ビューアを簡単に作成できるパッケージです。
2. Xcodeへのパッケージの追加
Xcode14では、「Package Dependencies」からパッケージを追加します。
(1) 「PROJECT」の「Package Dependencies」の「+」を押す。
![](https://assets.st-note.com/img/1676442521061-uMIPUhIIbM.png?width=800)
(2) 右上のテキストボックスに以下のURLを入力し、「ImageViewer」を選択し、「Add Package」ボタンを押す。
https://github.com/Krisiacik/ImageViewer
![](https://assets.st-note.com/img/1676442422114-4z8UYYkKJP.png?width=800)
3. Xcodeへのアセットの追加
今回は、1つのアセット画像 (cat)と、UIImageViewを配置したStoryboardを用意します。
![](https://assets.st-note.com/img/1676443742427-0c4IHJMFn2.png?width=800)
![](https://assets.st-note.com/img/1676443749471-GPPZLOH0k6.png?width=800)
4. コードの編集
ViewControllerを以下のように編集します。
import UIKit
import ImageViewer
// UIImageViewを移動可能に設定
extension UIImageView: DisplaceableView {}
class ViewController: UIViewController {
// Storyboardに設置したUIImageViewと関連付ける
@IBOutlet private weak var imageView: UIImageView!
// ロード時に呼ばれる
override func viewDidLoad() {
super.viewDidLoad()
// ImageViewにジェスチャーを設定
let tapGesture = UITapGestureRecognizer(
target: self,
action: #selector(didTap(_:)))
imageView.addGestureRecognizer(tapGesture)
imageView.isUserInteractionEnabled = true
}
// ImageViewタップ時に呼ばれる
@objc private func didTap(_ sender: UITapGestureRecognizer) {
// 画像をギャラリー表示
let viewController = GalleryViewController(
startIndex: 0,
itemsDataSource: self,
displacedViewsDataSource: self,
configuration: [
.deleteButtonMode(.none),
.thumbnailsButtonMode(.none)
])
presentImageGallery(viewController)
}
}
// GalleryItemsDataSource
extension ViewController: GalleryItemsDataSource {
// 要素数
func itemCount() -> Int {
return 1
}
// ギャラリー要素
func provideGalleryItem(_ index: Int) -> GalleryItem {
return GalleryItem.image { $0(self.imageView.image!) }
}
}
// GalleryDisplacedViewsDataSource
extension ViewController: GalleryDisplacedViewsDataSource {
// 移動可能要素
func provideDisplacementItem(atIndex index: Int) -> DisplaceableView? {
return imageView
}
}
5. 実行
UIImageViewをタップすることで、画像を拡大表示できることを確認します。
![](https://assets.st-note.com/img/1676443984303-FDzscs8Ot5.png?width=800)
この記事が気に入ったらサポートをしてみませんか?