๋ทฐ์ปจํธ๋กค๋ฌ์ ์คํฌ๋กค๋ทฐ๋ฅผ ์์ฑํด๋ณผ ์์ ์ด๋ค. ์๋์ ํ๋ฉด์ ๊ตฌํํด๋ณด์.
์คํฌ๋กค๋ทฐ์ ๋๊ฐ์ ๊ฒ์ ์ ๋ทฐ(firstView, secondView)๋ฅผ ์์ฑํ๋ค.
import UIKit
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .systemGray
return scrollView
}()
let firstView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let secondView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let thirdView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
}
}
๋ทฐ์ ์คํฌ๋กค๋ทฐ๋ฅผ ์ถ๊ฐํ๋ค. ๊ทธ๋ฆฌ๊ณ ์ค๋ ํท์ ์ฌ์ฉํ์ฌ ์คํ ๋ ์ด์์์ ์ค์ ํ๋ค. ์ค๋ ํท์ translatesAutoresizingMaskIntoConstraints = false๋ฅผ ์๋์ผ๋ก ํด์ฃผ๊ธฐ ๋๋ฌธ์ ์ถ๊ฐํ์ง ์์๋ ๋๋ค. ์คํฌ๋กค๋ทฐ์ ์์๋๋ ๋ทฐ์ ๊ฐ๊ฒ ํ๊ณ , ์ข์ฐ๋ ์ฝ๊ฐ์ ๊ฐ๊ฒฉ์ ๋์๋ค.
import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
...
view.addSubview(scrollView)
scrollView.snp.makeConstraints {
$0.top.bottom.left.right.equalToSuperview().inset(16)
}
}
}
์ฌ๊ฐํ๋ค์ ์คํฌ๋กค๋ทฐ์ ๋ฃ๋๋ค. ์ฌ๊ฐํ๋ค์ top๊ณผ left์ ์ก๊ณ ๋๋น์ ๋์ด๊ฐ์ ์ฃผ์๋ค. ์ฃผ์ํ ์ ์, ๋ง์ง๋ง ์ฌ๊ฐํ์์ bottom๊ฐ์ ๋ช ์ํด์ผ ์คํฌ๋กค์ด ์๋ํ๋ค๋ ๊ฒ์ด๋ค...!
class ViewController: UIViewController {
override func viewDidLoad() {
...
scrollView.addSubview(firstView)
scrollView.addSubview(secondView)
firstView.snp.makeConstraints {
$0.top.left.equalToSuperview()
$0.width.height.equalTo(100)
}
secondView.snp.makeConstraints {
$0.top.equalToSuperview().inset(1000)
$0.left.equalToSuperview()
$0.width.height.equalTo(100)
}
thirdView.snp.makeConstraints {
$0.top.equalToSuperview().inset(1000)
$0.left.equalToSuperview()
$0.bottom.equalToSuperview()
$0.width.height.equalTo(100)
}
}
}
import SnapKit
import UIKit
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .systemGray
return scrollView
}()
let firstView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let secondView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let thirdView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
view.addSubview(scrollView)
scrollView.addSubview(firstView)
scrollView.addSubview(secondView)
scrollView.addSubview(thirdView)
scrollView.snp.makeConstraints {
$0.top.bottom.equalToSuperview()
$0.left.right.equalToSuperview().inset(16)
}
firstView.snp.makeConstraints {
$0.top.left.equalToSuperview()
$0.width.height.equalTo(100)
}
secondView.snp.makeConstraints {
$0.top.equalToSuperview().inset(1000)
$0.left.equalToSuperview()
$0.width.height.equalTo(100)
}
thirdView.snp.makeConstraints {
$0.top.equalToSuperview().inset(2000)
$0.left.equalToSuperview()
$0.bottom.equalToSuperview()
$0.width.height.equalTo(100)
}
}
}