LoginSignup
22
22

More than 5 years have passed since last update.

Swift / 画面サイズより大きい画像をスクロールで表示できるようにする

Last updated at Posted at 2014-10-16

※2014/10/18 一部文言を修正。flashScrollIndicatorsについて追記。@takabosoft さん有り難うございます。

画像のスクロール表示はUIScrollViewを使う

画像の表示はUIImageViewにUIImageを埋め込むことで出来る。
 UIImageView > UIImage
スクロールはUIScrollViewに任意のViewを埋め込むことで出来る。
 UIScrollView > View

この二つから下のような親子関係にすれば画像をスクロール表示することが出来る。
 UIScrollView > UIImageView > UIImage

また、下記の2点を設定しないとうまくスクロール出来ませんでした。

  1. UIImageViewのフレームサイズをUIImageに合わせること
    • UIImageViewのイニシャライザでUIImageのサイズに合わせてくれるのであまり意識する必要はない
  2. UIScrollViewのcontentSizeプロパティをUIImageViewのフレームサイズと合わせること

UIScrollView表示時のスクロールバーをフラッシュ

UIScrollViewを表示する際はスクロールバーをフラッシュさせるflashScrollIndicators()を呼び出すべき。

Discussion
You should call this method whenever you bring the scroll view to front.

https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIScrollView_Class/index.html#//apple_ref/occ/instm/UIScrollView/flashScrollIndicators

サンプルコード内では下記に記述

スクロールバーのフラッシュ
    override func viewDidAppear(animated: Bool) {
        //UIScrollBar表示時にスクロールバーをフラッシュ表示
        scroll.flashScrollIndicators()
    }

サンプルコード

画像をスクロール表示
class ViewController: UIViewController {

    //StoryBoardからスクロールビューとイメージビューを関連づけ
    @IBOutlet var scroll: UIScrollView!
    @IBOutlet var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //UIImageに画像をセット
        let img:UIImage = UIImage(named: "hoge.jpg")

        //UIImageViewにUIImageをセット。UIImageViewのフレームサイズは
        //UIImageの画像サイズに自動的に合わせてくれる
        self.imageView = UIImageView(image: img)

        //画像の元サイズのままUIImageViewの左上に表示
        self.imageView.contentMode = UIViewContentMode.TopLeft

        //UIScrollViewにUIImageViewをセット
        self.scroll.addSubview(imageView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(animated: Bool) {
        //UIScrollBar表示時にスクロールバーをフラッシュ表示
        scroll.flashScrollIndicators()
    }

    override func viewDidLayoutSubviews() {
        //ScrollViewのサイズをImageViewに合わせる
        self.scroll.contentSize = self.imageView.frame.size

        //おまけ:ScrollViewの最下部にデフォルトの表示位置をセット
        self.scroll.contentOffset = CGPointMake(0, self.scroll.frame.height)
    }
}

scrollのcontentSizeをviewDidLayoutSubviews()で指定しているのは、AutoLayoutを使用した場合ここで記述しないとスクロールしてくれないという記事を見かけたからなのですが一応viewDidLoad内に記述してもスクロールしてくれました。
ただ後々詰まりそうなのでここに記述しています。そのあたりの細かいロジックは今後勉強していきたいなぁ。

これで想定動作はしているのですが、ただ何とも泥臭いやり方な気がします。(もはやストーリーボードがお払い箱というか...)
もっとスマートに出来る方法ないですかね〜。

22
22
2

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
22
22