LoginSignup
17
22

More than 5 years have passed since last update.

AutoLayoutを使ったUICollectionViewCellの動的なCellのサイズ調整(サンプルプロジェクトあり〼)

Posted at

やること

複数デバイスサイズでも、一行のセルの数が変わっても1枚のXibでコレクションのセルをある程度いい感じに動的にする

1個 2個 3個
スクリーンショット 2016-06-21 16.28.52.png スクリーンショット 2016-06-21 16.29.11.png スクリーンショット 2016-06-21 16.29.25.png

バージョン

iOS9以上
XCode7.2
で試してます。

手順

CollectionViewCellのXibと対応したClassを作成

CellいっぱいいっぱいのUIViewを設置して1.で作ったクラスのプロパティcontainerViewとして紐付ける

設置したUIViewをにオートレイアウト。ボトムだけ750に

スクリーンショット 2016-06-21 15.20.05.png

必要なものをレイアウトしていく。フレキシブルにしたい画像は上、左右だけ決めてアスペクト比のみ入力

スクリーンショット 2016-06-21 15.17.43.png
スクリーンショット 2016-06-21 17.14.30.png

上から順に一番したのアウトレットまでレイアウトを繋いでいき、最後のアウトレットのBottomとcontainerViewのBottomをつなぐ

CollectionViewControllerのデリゲートで以下のようにcontainerViewのフレームを返す

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let width = "セル1枚の横幅計算"
        let cell = "セル取得"

        var newFrame = cell.frame
        newFrame.size.width = width
        cell.frame = newFrame
        cell.layoutIfNeeded()
        return cell.containerView.frame.size
    }

Tips

  • sizeForItemAtIndexPathのたびにCellをインスタンス化してしまうと非常に遅くなるのでサイズをキャッシュさせる

サンプルプロジェクトはこちら

yo1106/AutolayoutSample

UITableViewはこちら

AutolayoutでCellの横幅いっぱいに画像を複数枚並べる

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