3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftUIでUICollectionViewのような表示をする

Last updated at Posted at 2019-12-28

SwiftUIではUICollectionViewの代わりになるものがない??

どうやらSwiftUIではUICollectionViewの完全に代わりになるものはないそうだ...

UIKit SwiftUI
UILabel Text
UIImageView Image
UITextField TextField
UITextView No equivalent (use Text/TextField
UISwitch Toggle
UISlider Slider
UIButton Button
UITableView List
UICollectionView No equivalent (can be implemented by List)
UINavigationController NavigationView
UITabBarController TabbedView
UIAlertController with style .alert Alert
UIAlertController with style .actionSheet ActionSheet
UIStackView with horizontal axis HStack
UIStackView with vertical axis VStack
UISegmentedControl SegmentedControl
UIStepper Stepper
UIDatePicker DatePicker
NSAttributedString No equivalent (use Text)

Listで表現できると書いてあるが、HStackとVStackでUICollectionViewを表現してみた!

ソースコード

import SwiftUI

struct TopView: View {

  let fibonacci = [
    ["0", "0.5", "1", "2"],
    ["3", "5", "8", "13"],
    ["21", "34", "55", "89"]
  ]

  var body: some View {
    HStack {
      NavigationView {
        VStack(alignment: .center, spacing: 30.0) {
          ForEach(0 ..< self.fibonacci.count) { section in
            HStack(alignment: .center, spacing: 50.0) {
              ForEach(0 ..< self.fibonacci[section].count) { row in
                Text("\(self.fibonacci[section][row])")
                  .font(.largeTitle)
                  .fontWeight(.heavy)
                  .multilineTextAlignment(.center)
              }
            }
            .padding(.all)
          }
        }
        .navigationBarTitle("Fibonacci")
      }
      .padding(.all)
    }
  }

}

struct TopView_Previews: PreviewProvider {
  static var previews: some View {
    TopView()
  }
}

 実行結果

  • image.png

  • image.png

 結論

  • HStackとVStackでViewを横と縦に繰り返し表示できれば、UICollectionViewのUIを表現することができそう...
  • QGridというSwiftUIのライブラリを使えばもっと楽に表現できそう...
    • QGridについては後日追記します!

追記

2019-12-31

  • QgridやStackをつかった構成で作成してみたが、UIKitのTableViewのようにCellを使いまわしてないので、1000件以上の表示になると重くなって全然ダメダメでした...
  • やっぱりListをうまく利用してUICollectionViewを再現できないか試していきます!
3
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?