LoginSignup
1
1

More than 1 year has passed since last update.

【SwiftUI】画面サイズに応じて広告数を変化させる

Posted at

はじめに

かなり限定的なお題ですが同じ事をする方がいると思うので記事にしておきます。

やりたい事

iPhone12 iPadPro11(縦) iPadPro11(横)
simulator_screenshot_2CBECF57-4401-4526-95D5-EC1044944B8B.png simulator_screenshot_9C0BCD94-3C2C-4E1E-BE31-E7A0A9DAC4DF.png simulator_screenshot_95EDA013-9111-40FF-AD02-4D3425A7CD71.png

このように画面の横幅によって横に並ぶ広告数を増やしていきたい。

条件

  • 左右にpaddingが20
  • HStackspacingは5
  • 広告の横幅は355以上408以下

全てのiPhoneとiPadで上記の条件をクリアしたい

実装

import SwiftUI

struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            HStack(alignment: .center, spacing: 5) {
                ForEach(0..<Int(geo.size.width)/355, id: \.self) { _ in
                    SmallNativeView()
                        .frame(minWidth: 355, maxWidth: 408, maxHeight: 76)
                        .cornerRadius(10)
                }
            }
            .padding(.horizontal, 20)
            .frame(width: geo.size.width, height: geo.size.height, alignment: .center)
        }
        .background(Color.yellow)
    }
}

ポイント
GeometryReaderを使用して動的な画面サイズを取得しています。

ポイント
frame(minWidth: 355, maxWidth: 408, maxHeight: 76)
minWidthmaxWidthを指定する事で自動でサイズ調整をしてくれます

ポイント
広告の横幅の基準は、
iPhoneの横幅から左右のpaddingの20を引いた数値を基準としています。

最大はiPhone13 Pro Maxで428
最小はiPhoneSEで375

よって、
広告1つの横幅は、最大408最小355となります。

ポイント
Int(geo.size.width)/355
画面サイズを広告の最小サイズで割る事で画面内に何個広告が表示できるかを計算しています。

おわり

広告を横に並べることはよくあると思うのでこの方法はかなり使えるのではないでしょうか。

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