[Swift]๋ค์ํ ๋๋ฐ์ด์ค์ ๋ง์ถฐ ์ ์ฌ์ด์ฆ๋ฅผ ์กฐ์ ํ๊ณ ์ ํ ๋ + ์ฌ์ด์ฆ๊ฐ ์ ๋ฐ๋์์ ๋ ํด๊ฒฐ๋ฐฉ๋ฒ (CollectionViewDelegateFlowLayout ํ๋กํ ์ฝ)
์ ๊ฐ ํ๋ฉด ์งค ๋๋ง๋ค ํท๊ฐ๋ฆฌ๋ ๋ถ๋ถ์ด๋ผ ์ ๋ฆฌํด๋ด ๋๋ค.
์ฝ๋ ์ ๋ทฐ์ ์ ์ฌ์ด์ฆ๋ฅผ ๋๋ฐ์ด์ค์ ๋ฐ๋ผ์ ์กฐ์ ํ๊ณ ์ถ์ ๋
์๋ฅผ ๋ค์ด ์ ๊ฐ ์ํ๋ ํ๋ฉด์ด ์๋์ ๊ฐ๋ค๊ณ ๊ฐ์ ํฉ์๋ค. ์ ๋ ์ฝ๋ ์ ๋ทฐ์์ ๋๊ฐ์ ์ ์ด ํ ์ค์ ์์นํ๊ณ , ๊ฐ ์ ์ฌ์ด์ ์ฌ๋ฐฑ์ 20์ด๋ฉฐ, ์ ์ ๋น์จ์ 1:1.4์ ๋์ ํฌ๊ธฐ๋ฅผ ์ํ๊ณ , inset์ด ํ๋ฉด ์ข์ฐ์ ์๊ธธ ์ํฉ๋๋ค. ์ ๋ ์ ๊ฐ ์์ดํฐ 13 ๋ฏธ๋๋ฅผ ์ฐ๋ , ๋งฅ์ค๋ฅผ ์ฐ๋ ๋ณด์ด๋ ๋ชจ์์๊ฐ ์๋์ ๋์ผํ๊ณ ์ถ์ต๋๋ค.
์ด๋ ๊ฒ ์ผ๊ด๋ ํ๋ฉด์ ๋ณด์ฌ์ฃผ๊ธฐ ์ํด์ ์ ๋ ํด๋น ํ๋ฉด์ ๋ด๋นํ๋ UIViewController์ UICollectionViewDelegateFlowLayout ํ๋กํ ์ฝ์ ์์๋ฐ์ต๋๋ค.
UIViewController : UIViewController, UICollectionViewDataSource,
UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// code ์์ญ
override func viewDidLoad() {
super.viewDidLoad()
}
}
CollectionView๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํด์ ๊ธฐ๋ณธ์ ์ผ๋ก ํ์ํ ํ๋กํ ์ฝ์ธ UIViewcontroller, UICollectionViewDataSource์ UICollectionViewDelegate ๋ฅผ ํฌํจํ์ฌ ์ด๋ ๊ฒ ์ผํ๋ก ๊ตฌ๋ถํ์ ์์ํ ์ ์์ง๋ง ๊ฐ๋ ์ฑ๊ณผ ํธ์์ฑ์ ์ํด extension์ผ๋ก ๋ฐ๋ก ์ ๋ฆฌํฉ๋๋ค.
extension UIViewController : UICollectionViewDelegateFlowLayout {}
ํด๋น ํ๋กํ ์ฝ์์ ์ ์ ์ฌ์ด์ฆ๋ฅผ ๊ฒฐ์ ํ๋ ๊ฒ์ collectionView ๋ฉ์๋ ์ค sizeForItemAt ์ธ์๊ฐ ์๋ ๋ฉ์๋๋ฅผ ๋ถ๋ฌ์ ์ ์ํด์ฃผ๋ฉด ๋ฉ๋๋ค.
์ ํ๋ฉด์ ํ ๋๋ก ์์ฑ๋ ์ฝ๋๋ ์๋์ ๊ฐ์ต๋๋ค.
extension UIViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let margin: CGFloat = 20
let width: CGFloat = (collectionView.bounds.width - margin) / 2
let height: CGFloat = width * 1.4
return CGSize(width: width, height: height )
}
}
* ํด๋น ์ฝ๋ ์ ๋ทฐ์ ๊ฐ๋ก๊ธธ์ด๋ฅผ ๊ตฌํ๋ ๋ฐฉ๋ฒ
CollectionView.bounds.width
CGSize๋ผ๋ ํํ๋ก ์ฌ์ด์ฆ๋ฅผ ๋ฆฌํดํด์ผํ๊ธฐ ๋๋ฌธ์, ์ฌ์ด์ฆ์ ๊ด๋ จ๋ ๋ณ์๋ค์ CGFloat ์ผ๋ก ํ์ ๋ช ์๋ฅผ ํด์ฃผ์์ต๋๋ค.
๊ผญ ํ์ธํ ๋ถ๋ถ
(์ ์ฝ๋๋๋ก ์๋ฎฌ๋ ์ดํฐ์์ ๋ณด์ด์ง ์๋๋ค๋ฉด ์ด ๋ถ๋ถ์ ๊ผญ ์ฒดํฌํด๋ณด์ธ์)
์ฌ๊ธฐ์ ์ค์ํ ๊ฒ์ ํด๋น ์ฝ๋ ์ ๋ทฐ์ Size Inspector์์ Estimate size ๋ฅผ None์ผ๋ก ์ค์ ํด์ฃผ์ด์ผ ํฉ๋๋ค.
์ฐธ๊ณ ๋ก ์ด ์ฌ์ด์ฆ ์ธ์คํํฐ์์ ์ ๊ณผ ํ๊ฐ ์ฌ๋ฐฑ, ํค๋ ๋ฐ ํธํฐ ์ฌ์ด์ฆ, ์น์ inset์ ์ง์ ํด์ค ์ ์์ต๋๋ค. ์ฌ๊ธฐ์ Inset์ ์ง์ ํด์ฃผ์๋ค๋ฉด ์์ ์ฝ๋ ์์ญ์์ ํด๋น inset ๊ฐ์ ํฌํจํ์ฌ ์ ์ฌ์ด์ฆ๋ฅผ ๊ณ์ฐํด์ฃผ์ด์ผ ํฉ๋๋ค.
๋ง์ฝ Automatic์ผ๋ก ํ ๊ฒฝ์ฐ, ์์ฒด์ ์ผ๋ก ์คํ ๋ฆฌ๋ณด๋์์ ์ง์ ํด์ค ์ ์ฌ์ด์ฆ์ ์คํ ๋ ์ด์์์ ํตํด ์ ์ฌ์ด์ฆ๋ฅผ ๊ณ์ฐํ๋ฏ๋ก ๋๋ฐ์ด์ค์ ๋ฐ๋ผ ์๋ํ ํํ๋๋ก ํํ๋์ง ์์ ์ ์์ต๋๋ค.
์ฐธ๊ณ ๋งํฌ
1. UICollectionViewDelegateFlowLayout ๋ฌธ์
https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout
Apple Developer Documentation
developer.apple.com
2. collectionView(_:layout:sizeForItemAt:)
Apple Developer Documentation
developer.apple.com
๋ง์น๋ฉฐ
์ค๋๋ ์ฝ์ด์ฃผ์ ์ ๊ฐ์ฌํฉ๋๋ค.
๊ถ๊ธํ ์ ์ด ์๋ค๋ฉด ๋๊ธ๋ก, ๋์์ด ๋์ จ๋ค๋ฉด ๊ณต๊ฐ ๋ถํ๋๋ฆฝ๋๋ค.
ํน์ ์์ ํ๊ฑฐ๋ ํผ๋๋ฐฑํ์ค ๋ด์ฉ ์๋ค๋ฉด ์ธ์ ๋ ๋๊ธ๋ก ๋ถํ๋๋ฆฝ๋๋ค.
๊ฐ์ฌํฉ๋๋ค.
๋๊ธ