– StackView, ScrollView, TableView, CollectionView
UIKit으로 UI 설계하는 게 처음이라 뭐부터 시작하면 좋을 지 모르겠어서
튜터 님께 조언을 구해보니 위의 네 개 뷰를 알면 좋을 거 같다고 말씀해주셔서 톺아봄 !!
iOS 앱을 만들다 보면 화면에 버튼, 이미지, 리스트 같은 것들을 배치해야 할 때가 있는데 그럴 때 알아야 할 네 가지 뷰를 알아보려 함 !!
여러 개의 뷰(Button, Label 등)를 수직 또는 수평 방향으로 차곡차곡 정렬해주는 컨테이너 뷰
뷰를 나란히 정렬할 때 간편함
코드/스토리보드 둘 다에서 자주 쓰임
반응형(화면 크기 변화 대응)에 유리함
| 장점 | 단점 |
|---|---|
| 자동 정렬, 코드 간단 | 복잡한 레이아웃에 한계 |
let stackView = UIStackView()
stackView.axis = .vertical // 세로 방향
stackView.spacing = 10 // 간격
stackView.alignment = .fill
stackView.distribution = .fillEqually
let label = UILabel()
label.text = "아이디"
let textField = UITextField()
textField.borderStyle = .roundedRect
stackView.addArrangedSubview(label)
stackView.addArrangedSubview(textField)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.widthAnchor.constraint(equalToConstant: 200)
])
한 화면에 다 안 들어가는 내용을 스크롤해서 볼 수 있게 해주는 뷰
(세로, 가로 모두 가능)
긴 글, 이미지, 폼 등을 보여줘야 할 때
화면 제한 없이 스크롤로 모든 콘텐츠 표시 가능
| 장점 | 단점 |
|---|---|
| 무한 스크롤, 다양한 콘텐츠 배치 | 오토레이아웃이 복잡할 수 있음 |
let scrollView = UIScrollView()
scrollView.frame = view.bounds
view.addSubview(scrollView)
let contentView = UIView()
contentView.frame.size = CGSize(width: view.bounds.width, height: 1500)
scrollView.addSubview(contentView)
scrollView.contentSize = contentView.frame.size
let label = UILabel(frame: CGRect(x: 20, y: 50, width: 300, height: 40))
label.text = "스크롤 가능 영역"
contentView.addSubview(label)
데이터를 세로로 긴 리스트 형태로 표현할 때 사용하는 뷰
연락처 목록, 뉴스 기사 등 일렬로 나열된 항목에 적합
많은 데이터를 효율적으로 보여줌
스크롤 자동 처리 + 셀 재사용으로 성능도 좋음
| 장점 | 단점 |
|---|---|
| 셀 재사용으로 성능 우수, 구현 간단 | 세로 방향만 지원, 셀 커스터마이징 어려움 |
class ViewController: UIViewController, UITableViewDataSource {
let tableView = UITableView()
let data = ["사과", "바나나", "체리"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
}
셀을 격자 형태, 가로/세로 방향, 다양한 레이아웃으로 배치할 수 있는 뷰
테이블뷰보다 자유로운 레이아웃 지원
사진 그리드, 카드 레이아웃 등 다양한 형태의 UI
셀 크기, 간격, 방향 자유롭게 설정 가능
| 장점 | 단점 |
|---|---|
| 자유로운 레이아웃, 가로/세로 스크롤 가능 | 구현 복잡, 처음엔 어려움 |
class ViewController: UIViewController, UICollectionViewDataSource {
var collectionView: UICollectionView!
let data = ["🍎", "🍌", "🍒"]
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 80, height: 80)
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 10
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.backgroundColor = .white
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
for subview in cell.contentView.subviews { subview.removeFromSuperview() }
let label = UILabel(frame: cell.contentView.bounds)
label.text = data[indexPath.item]
label.font = UIFont.systemFont(ofSize: 40)
label.textAlignment = .center
cell.contentView.addSubview(label)
cell.backgroundColor = .lightGray
return cell
}
}
| 뷰 이름 | 특징 | 사용처 |
|---|---|---|
| UIStackView | 뷰를 수직/수평으로 자동 정렬 | 폼 입력, 버튼 배열 등 기본 UI 구성 |
| UIScrollView | 화면 넘치는 내용 스크롤로 표시 가능 | 긴 글, 이미지 뷰어, 폼 작성 화면 |
| UITableView | 세로로 긴 목록, 성능 최적화된 리스트 | 친구 목록, 뉴스 리스트, 주문 내역 |
| UICollectionView | 격자/가로/세로 자유로운 셀 배치 | 피드 화면, 카드 레이아웃, 갤러리 |