15
8

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 1 year has passed since last update.

paddingとspacingの違い(SwiftUI)

Last updated at Posted at 2023-04-30

結論

用語 意味 主な用途 備考
padding 要素の 内側 の余白 親要素との間に余白を設ける
ボタンの見た目を変えずにタップ領域を広げる
Webの padding と同義
spacing 要素同士の間隔(要素の 外側 の余白) 要素間に余白を設ける Webの gap と同義

環境

  • OS:macOS Ventura 13.3.1
  • Xcode:14.3 (14E222b)
  • Swift:5.8

「padding」とは?

SwiftUIにおけるViewのモディファイアで、指定した方向に指定した値だけ余白を付けます。

Webのpaddingと同様で、要素の 内側 に余白を付けます。
つまりViewのサイズ( frame )に影響を与えます。

「spacing」とは?

VStackHStack などのイニシャライザで指定できる値で、指定した値だけサブビュー間に余白を設けます。
Webのgapと同様と考えるとわかりやすいです。

padding と異なり、要素の 外側 に余白を付けます。
Viewのサイズに影響を与えません。

主な用途

TBD

おまけ: コンポーネントがmarginを持つと○ぬ

Webで言われている名言です。

○ぬ理由をわかりやすく説明している引用リツイートがあったので紹介します。

SwiftUIでも同様であり、要素同士の間隔は親要素の spacing で決めるべきです。

// ✅
VStack(spacing: 8) { // 親
  Image(systemName: "swift") // 子
  Text("Swift") // 子
}

// ❌
VStack(spacing: 0) { // 親
  Image(systemName: "swift") // 子
    .padding(.bottom, 8)
  Text("Swift") // 子
}

おわりに

誤っていたらご指摘ください :pray:

15
8
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
15
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?