[Swift] Anchor ์ฌ์ฉํด์ UIView ๋ฃ๊ธฐ
๋ค์ด๊ฐ๊ธฐ์ ์์...
Programmatically ๋ทฐ์ ๋ทฐ๋ฅผ ์ถ๊ฐํ๋ ๋ฐฉ๋ฒ์ ๋๋ค. interface builder ์์ UIView๋ฅผ ์ถ๊ฐํ๊ณ frame์ ์ง์ ํด ์ค๋ ๋์ง๋ง ์ฝ๋๋ก view๋ฅผ ์์ฑํด์ addSubView ํด์ฃผ๊ฑฐ๋ ํด๋ํฐ ๋ฐฉํฅ(width๊ฐ ๋ฐ๋๋ ๊ฒฝ์ฐ), safe Area ๋ฑ์ Anchor๋ฅผ ์ด์ฉํ๋ ๊ฒ์ด ํธํ ๋๊ฐ ์์ต๋๋ค.
์ด์ ์ ํฌ์คํ ํ collectionView์์ ์์ํ๋ฉฐ ์ด๋ ๋ฐ์ํ ์ค๋ฅ๋ width๊ฐ ์ ๋๋ก ๋์ค์ง ์์ ์งค๋ฆฌ๋ ๊ฒฝ์ฐ์์ต๋๋ค. Anchor๋ฅผ ํตํด์ ์ด๋ป๊ฒ ๊ณ ์น ์ ์๋์ง ์์๋ด ์๋ค.
์ฝ๋๋ฅผ ์ด์ฉํ์ฌ view๋ฅผ ์์ฑํด์ ๋ฃ์ด์ฃผ๊ธฐ ์ํด storyboard์ ์ถ๊ฐํ ๋ทฐ๋ฅผ ์ญ์ ํด์ฃผ์์ต๋๋ค
์ฐ๊ฒฐ๋ IBOutlet ์ญ์ ๋ ๊ผญ ํด์ค๋๋ค
ViewController.swift ํ์ผ๋ก ๊ฐ๋๋ค
์ฐ์ ์ถ๊ฐํด ์ค ๋ทฐ์ธ UICollectionView๋ก ์ ์ธํด ์ค ํ๋กํผํฐ์์
translatesAutoresizingMaskIntoConstraints๋ฅผ false๋ก ์ง์ ํด ์ค๋๋ค.
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.scrollDirection = .vertical
layout.sectionInset = .zero
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .green
// collectionView์ Autorezing mask๋ฅผ false๋ก ์ง์ ํด ์ค๋๋ค
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
์ฝ๋๋ก ์ ์ฝ ์ฌํญ์ ์ง์ ํด ์ค ๊ฒ์ด๊ธฐ ๋๋ฌธ์
autoresizing mask๋ฅผ false๋ก ์ง์ ํด ์ฃผ๋ ๊ฒ์ ๋๋ค.
+) default ๊ฐ์ true
๋ค์์ viewDidLoad()๋ฅผ ์์ฑํด ์ค๋๋ค
๋ทฐ๊ฐ ๋ก๋ ๋ ๋ self.view์ collectionView๋ฅผ ๊ณ์ธต ๊ตฌ์กฐ์ ์ถ๊ฐํด ์ฃผ๊ฒ ์ต๋๋ค.
anchor๋ฅผ ์ฌ์ฉํ ๋ ์ฃผ์ ํ ์ ์ anchor๋ง ์ง์ ํ๋ค๊ณ ๋๋ ๊ฒ์ด ์๋๋ผ
๊ณ์ธต ๊ตฌ์กฐ์ ์ถ๊ฐํด ์ฃผ์ด์ผ ์ ์ฝ ์กฐ๊ฑด์ ์ฝ๋๋ก ์์ฑํ ์ ์๋ค๋ ๊ฒ์ ๋๋ค.
view.addSubview(collectionView)
์ด์ constraints๋ฅผ ์์ฑํด ์ค๋๋ค
์ด constraints๋ activate ํด์ฃผ์ด์ผ ์คํ๋ฉ๋๋ค. ์๋์ ๊ฐ์ด ์์ฑํด ์ค๋๋ค.
let constraints = [
collectionView.heightAnchor.constraint(equalToConstant: 180),
collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 300)
]
NSLayoutConstraint.activate(constraints)
collectionView์ ๋์ด๋ฅผ 180์ผ๋ก ์ง์ ํ๊ณ
collectionView์ leading์ self.view์ leading๊ณผ 0์ผ๋ก ์ง์ ํ๋ฉด
collectionView์ ์์์ ์ด view์ ์์์ ๊ณผ ๊ฐ์์ง๋๋ค
trailing๋ ๋๊ฐ์ด ์ง์ ํด ์ค๋๋ค
์ด๋ bottom์ ์ ์์ฑํ๊ณ top๋ง ์ง์ ํด ์ฃผ๋ ์ด์ ๋
๋์ด๊ฐ ์๊ธฐ ๋๋ฌธ์ ๋ ์ด์์ ์ ์ค๋ฅ๊ฐ ์์ต๋๋ค.
์คํํด ๋ณด๋ฉด
์ด๋ฌํ ๊ฒฐ๊ณผ๋ฅผ ์ป์ ์ ์์ต๋๋ค
์ xcode 12 Show Quick Help inspector์ Open in Developer Documentation ๋๋ฅด๋ฉด
xcode ์ข ๋ฃ๋๋ ๊ฑด๊ฐ์... ๐ง๐ง๐ง
ํ๋ฆฌ๊ฑฐ๋ ์ด์ํ ๋ถ๋ถ์ด ์๋ค๋ฉด ๋๊ธ ๋ถํ๋๋ ค์! ์ธ์ ๋ ํ์์ ๋๋ค!