4
4

More than 1 year has passed since last update.

【SwiftUI】モディファイアを条件によって変える

Last updated at Posted at 2022-07-05

はじめに

今回作成するサンプルはindexが3の倍数の場合にpaddingを付けるというものです。
いい案が思いつかなかったので、サンプルとしてはわかりにくいかも知れないです笑
完成形はこのような形になります。
simulator_screenshot_606CF1B6-853E-400A-A0E9-684FC1AD1D5F.png

やり方

Viewを拡張してif文で条件分岐します。

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            ForEach(0..<30) { index in
                Text("テキスト \(index)")
                    .listPadding(index)
            }
        }
    }
}

extension View {
    func listPadding(_ index: Int) -> some View {
        return padding(.leading, index % 3 == 0 ? 30 : 0)
    }
}

おわり

私はよく端末によってモディファイアを変更する際に使用しています。
こんな感じ ↓

extension View {
    func trailingPadding() -> some View {
        return padding(.trailing, UIDevice.current.userInterfaceIdiom == .pad ? 17 : 3)
    }
}

あげたサンプルコードは全てpaddingでしたがどのモディファイアでも可能です。

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