はじめに
今回作成するサンプルはindexが3の倍数の場合にpaddingを付けるというものです。
いい案が思いつかなかったので、サンプルとしてはわかりにくいかも知れないです笑
完成形はこのような形になります。
やり方
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
でしたがどのモディファイアでも可能です。