LoginSignup
0
4

More than 3 years have passed since last update.

SwiftUIで画面の大きさに応じて内容が変わるビューを作る

Posted at

GeometryReaderを使うと、ビューのサイズを取得できる。

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            Text("\(Int(geometry.size.width)) x \(Int(geometry.size.height))")
        }
    }
}

スクリーンショット 2020-05-03 15.44.14.png

取得したサイズによって、表示する内容を変化させることでレスポンシブなビューを作ることができる。下のコードでは、横幅が800px未満の時はビューを縦に並べ、800px以上の時は横に並べている。

struct ContentView: View {
    var body: some View {
        GeometryReader<AnyView> { geometry in
            if geometry.size.width < 800 {
                return AnyView(VStack{
                    Color.red
                    Color.blue
                })
            } else {
                return AnyView(HStack{
                    Color.red
                    Color.blue
                })
            }
        }
    }
}

横幅が800px未満のとき
スクリーンショット 2020-05-03 15.55.55.png

縦幅が800px以上のとき
スクリーンショット 2020-05-03 15.55.58.png

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