어제 논의했던 와이어프레임과 기획 내용을 바탕으로 내가 담당하게된 미들 부분은
메뉴의 이미지와 이름, 가격이 들어가는 메인 메뉴 파트다
해당 부분은 Collection View(컬렉션뷰)를 사용하는 것이 프로젝트 과제 조건이었다!
컬렉션뷰는 처음 사용하는 거라 내용을 간단하게 찾아 보았다
컬렉션뷰란?
정렬된 데이터 아이템 모음을 관리하고, 사용자 레이아웃으로 유연하게 표현이 가능한 객체
동일한 기능과 레이아웃을 가진 view 들을 재사용 할 수 있다
메인 메뉴 이미지를 참고하자면, 동일한 규격의 View 내부에 이미지와 텍스트만 달라지는 건데,
해당 부분은 컬렉션뷰를 이용하는 것이 적합한 것 같았다
이것 저것 찾아보면서 완성한 코드.. 인줄 알았는데 🚨 오류 발생 🚨
import UIKit
import SnapKit
//음료 정보 텍스트를 담을 클래스
class CustomCollectionViewCell: UICollectionViewCell {
let label: UILabel = {
let drink = UILabel()
drink.backgroundColor = .white
drink.textColor = .black
drink.textAlignment = .center
drink.font = UIFont.systemFont(ofSize: 14)
return drink
}()
//UICollectionViewCell의 초기화 메서드
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(label)
label.snp.makeConstraints { make in
make.top.equalToSuperview().offset(150)
make.height.equalTo(20) // 텍스트 높이
}
self.backgroundColor = .white
}
required init?(coder: NSCoder) {
fatalError("*T_T*")
}
}
//컬렉션뷰
class SBMenuController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .white
return cv
}()
// 이미지 배열
let img = CoffeeList.smoothie_Menu
//컬렉션뷰를 뷰에 추가하고 데이터소스 및 델리게이트를 설정
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
configureCollectionView()
}
func configureCollectionView() {
collectionView.snp.makeConstraints { make in
make.top.equalToSuperview().offset(180)
make.leading.equalToSuperview().offset(20)
make.trailing.equalToSuperview().offset(-20)
make.bottom.equalToSuperview().offset(-20)
}
// 셀 등록
collectionView.register(MenuView.self, forCellWithReuseIdentifier: "img")
}
//컬렉션뷰 내 셀 항목(수량)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return img.count // 예시 항목 개수
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "img", for: indexPath) as! MenuView
let menuItem = img[indexPath.item]
cell.imgView.image = UIImage(named: menuItem.imageName)
cell.label.text = ("Item \(indexPath.row)")
return cell
}
// UICollectionViewDelegateFlowLayout 메서드
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 110, height: 130) // 텍스트 공간 포함 크기
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 80
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
}
🚨 오류 발생 내용
오류 1) 검은색 테두리 생김..
→ view의 컬러가 정해지지 않아서 collection view를 제외한 공간의
백 그라운드 컬러가 black 으로 설정된 것이었음
아래와 같이 view의 background 컬러 설정 후 해결 완료 👏🏻
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white //추가한 코드
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
configureCollectionView()
}
오류 2) text 가 왼쪽으로 쏠림
현재 사진 상으로는 정 중앙에 위치하나 왼쪽으로 쏠리는 현상 발생textAlignment = .center 설정했으나 여전히 동일하게 왼쪽 쏠림
→ label의 Constaraints가 height만 설정되어 추가로 width 설정 후 해결 완료 👏🏻
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(label)
label.snp.makeConstraints { make in
make.top.equalToSuperview().offset(150)
make.height.equalTo(20)
make.width.equalTo(110) //추가한 코드
}
오류 해결 후 전체 코드
두 가지 오류 해결 후 완성된 인터페이스 와 코드
따로 만들어둔 Asset 이미지도 잘 끌어오고, 예쁘게 잘 뜬다!
여기까지 하는데 하루종일 + 새벽 4시.......🙂↔️
import UIKit
import SnapKit
//음료 정보 텍스트를 담을 클래스
class CustomCollectionViewCell: UICollectionViewCell {
let label: UILabel = {
let drink = UILabel()
drink.backgroundColor = .white
drink.textColor = .black
drink.textAlignment = .center
drink.font = UIFont.systemFont(ofSize: 14)
return drink
}()
//UICollectionViewCell의 초기화 메서드
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(label)
label.snp.makeConstraints { make in
make.top.equalToSuperview().offset(150)
make.height.equalTo(20) // 텍스트 높이
make.width.equalTo(110) // 텍스트 너비
}
self.backgroundColor = .white
}
required init?(coder: NSCoder) {
fatalError("*T_T*")
}
}
//컬렉션뷰
class SBMenuController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .white
return cv
}()
// 이미지 배열
let img = CoffeeList.smoothie_Menu
//컬렉션뷰를 뷰에 추가하고 데이터소스 및 델리게이트를 설정
override func viewDidLoad() {
super.viewDidLoad()
//뷰 백그라운드컬러 안 정해주면 안됨!!!!!!!!!!!!!
view.backgroundColor = .white
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
configureCollectionView()
}
func configureCollectionView() {
collectionView.snp.makeConstraints { make in
make.top.equalToSuperview().offset(180)
make.leading.equalToSuperview().offset(20)
make.trailing.equalToSuperview().offset(-20)
make.bottom.equalToSuperview().offset(-20)
}
// 셀 등록
collectionView.register(MenuView.self, forCellWithReuseIdentifier: "img")
}
//컬렉션뷰 내 셀 항목(수량)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return img.count // 예시 항목 개수
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "img", for: indexPath) as! MenuView
let menuItem = img[indexPath.item]
cell.imgView.image = UIImage(named: menuItem.imageName)
cell.label.text = ("Item \(indexPath.row)")
return cell
}
// UICollectionViewDelegateFlowLayout 메서드
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 110, height: 130) // 텍스트 공간 포함 크기
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 80
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
}
각자 작업한 코드 Merge 진행
하려고 했으나 계속되는 Conflict 발생 + Comit 시 코드 사라짐 ㅋㅋㅋㅋ
또 우르르 튜터님 찾아갔다
그리고 충격적인 사실을 알게 되는데
컴플릭이 많이 났던 이유 = 깃 이그노어(gitignore) 안 해서...
처음에 레포 만들 때부터 깃 이그노어 해야한다고 한다
그래서 뒤늦게 추가함 ㅎㅎ
이제 곧 각자 중간 완성된 작업물을 합쳐서 연결하고, 필요한 추가기능을 구현할 예정이다
오늘 TIL 끝 💫
'💻 스파르타코딩클럽 > 팀 프로젝트' 카테고리의 다른 글
[세번째 팀 프로젝트] 킥보드 쉐어링 앱 1️⃣ (1) | 2024.07.22 |
---|---|
[두번째 팀 프로젝트] 모바일 키오스크 4️⃣ (0) | 2024.07.11 |
[두번째 팀 프로젝트] 모바일 키오스크 3️⃣ (1) | 2024.07.05 |
[두번째 팀 프로젝트] 모바일 키오스크 1️⃣ (0) | 2024.07.02 |
[첫번째 팀 프로젝트] 자기소개 앱 만들기 (0) | 2024.05.30 |