Bibi's DevLog ๐Ÿค“๐ŸŽ

[Swift] ์ฝ”๋“œ๋กœ AutoLayout ์„ค์ •ํ•˜๊ธฐ (Constraint) ๋ณธ๋ฌธ

๐Ÿ“ฑ๐ŸŽ iOS

[Swift] ์ฝ”๋“œ๋กœ AutoLayout ์„ค์ •ํ•˜๊ธฐ (Constraint)

๋น„๋น„ bibi 2022. 4. 8. 00:01

[Swift] ์ฝ”๋“œ๋กœ AutoLayout ์„ค์ •ํ•˜๊ธฐ (Constraint)

https://macgongmon.club/31

์ฐธ๊ณ ํ•˜๊ธฐ : Apple ๊ณต์‹ ๋ฌธ์„œ: Understanding Auto Layout

AutoLayout์ด๋ž€

: ๋ทฐ ๊ณ„์ธต ๋‚ด์—์„œ ๋ทฐ๋“ค์˜ ํฌ๊ธฐ์™€ ์œ„์น˜๋ฅผ ๊ฐ ๋ทฐ๋“ค์˜ ์ œ์•ฝ์‚ฌํ•ญ(constraint)์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ ์œผ๋กœ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ.

์—ฌ๋Ÿฌ ํ•ด์ƒ๋„๋ฅผ ์œ ์—ฐํ•˜๊ฒŒ ์ง€์›ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

AutoLayout vs Frame-Based Layout

  • Frame-Based Layout
    • ์ •์˜๋œ ์ขŒํ‘œ(origin - X, Y)์™€ ์‚ฌ์ด์ฆˆ(size - width, height)์— ๋”ฐ๋ผ ๋ทฐ๊ฐ€ ๊ทธ๋ ค์ง„๋‹ค.
  • AutoLayout
    • ์ •์˜๋œ ์ œ์•ฝ์‚ฌํ•ญ(constraint)์— ๋”ฐ๋ผ ๋ทฐ๊ฐ€ ๊ทธ๋ ค์ง„๋‹ค.
    • constraint = ์ง€๊ธˆ ๋ทฐ์˜ ๋„ˆ๋น„, ๋†’์ด ๋ฐ ์–ด๋–ค ๋ทฐ๋กœ๋ถ€ํ„ฐ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์ ธ ์žˆ๋Š”์ง€ ๋“ฑ์„ ๋‚˜ํƒ€๋ƒ„
      • width, height, top, bottom, left, right, leading, trailing, centerX, centerY ...

Contstraint

  • top์™€ leading, bottom๊ณผ trailing
    • ํ˜„์žฌ ์œ„์น˜์—์„œ "์™ผ์ชฝ์œผ๋กœ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์งˆ์ง€" : ๋Š” ์–‘์ˆ˜๋กœ ์„ค์ • (ex - constant: 10)
    • ํ˜„์žฌ ์œ„์น˜์—์„œ "์˜ค๋ฅธ์ชฝ์œผ๋กœ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์งˆ์ง€" : ๋Š” ์Œ์ˆ˜๋กœ ์„ค์ • (ex - constant: -10)
  • centerX, centerY : x/y์— ๋Œ€ํ•œ ์ค‘์•™๊ฐ’

AutoLayout ์„ค์ •ํ•˜๊ธฐ

  1. UI ์š”์†Œ๋“ค ์ •์˜ํ•˜๊ธฐ
    1. AutoLayout์„ ์„ค์ •ํ•  ๋ทฐ์— ๋Œ€ํ•ด ๋ฐ˜๋“œ์‹œ .translateAutoresizingMaskIntoConstraints = false๋กœ ์„ค์ •ํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
    2. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.
  2. addSubView๋กœ ์ถ”๊ฐ€ํ•˜๊ธฐ
    1. self.addSubview(์ถ”๊ฐ€ํ• ๋ทฐ)
  3. bind Constraints - ๋ทฐ์— ์ œ์•ฝ์‚ฌํ•ญ ์„ค์ •ํ•˜๊ธฐ
    1. topAnchor, bottomAnchor, leftAnchor, rightAnchor
    2. widthAnchor, heightAnchor
    3. centerXAnchor, centerYAnchor
    4. leadingAnchor, trailingAnchor