본문 바로가기

iOS 앱 개발자 프로젝트/iOS 심화

[iOS] bookStore app project (2)

지난 글에 이어 시작해 봅니다. 

UI 컴포넌트들을 추가하고 snapKit으로 autolayout 잡은 것까지 오늘 올리고,

api를 연결한 network manager는 내일 업로드 하겠습니다. 

 

힘내자아아...  •̤᷆ ₃ •̤᷇ ฅ


snapKit 설치  → VC에 import 완료!

main 및 info.plist 수정, 삭제 완료!

 

 codebaseUI 내용을 떠올리며,

scene delegate도 수정!  본격적으로 시작할 준비 완료!

 

 

인줄 알았는데?!

 

프로젝트 생성할 때 code data 체크 안했네.. ?

아래 코드 app delegate에 core data stack과 core data saving support 추가해서 진짜 준비 완!? 

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {

        
        let container = NSPersistentContainer(name: "CoreData")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
          if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        })
        return container
      }()

    // MARK: - Core Data Saving support

    func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

 

 

 

준비가 과정이고 과정이 준비고..

이제 UI를 섹션별로 어떻게 구성할 것인지에 대한 준비 시작..

 

답이 정해진 건 아니므로 창의성을 발휘해(?) 효율적으로 UI 컴포넌트 별 프로퍼티를 만들어준다.

 

 

 

| #1. tabbarController  @ Scene Delegate

 

기존 VC 는 fistVC로,  secondVC도 추가한 후,

아래와 같이 tabbarItem을 사용해서  tab에 보여질 아이콘을 설정해 준다.

 

화면이 뜨는 시점에서 구현되도록 sceneDelegate에서 코드를 넣어준다.**

B&A : WWDC 2019에 발표된, iOS13부터 적용 가능한 fter checkout! (Scene Delegate 분리!)

 

 

 firstVC & seconVC tabbarItem (selected 버전은 .fill 아이콘으로 넣었다.)

 


 

 

 

 

| #2. UISearchBar, UILabel, UICollectionView, UITableView @ VCs - ViewController

 

bar.placeholder로 search bar 안에 보여질 문구도 넣어주고,

    lazy var searchBar : UISearchBar = {
        let bar = UISearchBar()
        bar.placeholder = "찾고 싶은 책의 이름을 입력하세요"
        return bar
    }()

VC에서 UI component별 property 만들기

 

layout 함수로 subview를 만들고 viewDidLoad에서 호출해준다.

   override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        layout()

 

 

addSubview로 만든 하위 계층들 모두 forEach 문으로 정리해주면 깔끔.! 이 요소들로 레이아웃을 잡아주면 된다.

layout func + snapkit autoLayout ( layout() 호출하기 잊지마.. )

 


 

| #3. UIStackView, UITableView @ VCs - SecondViewController

 

전체삭제(button), 담은책(label), 추가(button) 을 horizontal stackView로 묶어주고,

담은 책 목록은 tableView로 프로퍼티를 만든다.

2ndVC에서 UI component별 property 만들기

 

 

버튼의 텍스트를 입력할 때 text 나 title이 아닌, setTitle이라는 것을 기억해..

버튼 텍스트의 컬러를 수정할 때도 button.setTitleColor(.color,for:_) 이렇게..

 

label은 label.text 로 입력하지만,

button은 button.setTitle("", for:_)다.

    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setTitle("전체 삭제", for: .normal)
        button.backgroundColor = .white
        button.setTitleColor(.red, for: .normal)
        return button
    }()
    private lazy var bookLabel: UILabel = {
        let label = UILabel()
        label.text = "담은 책"
        label.textAlignment = .center
        label.textColor = .black
        return label
    }()

 

 

그리고 양 끝의 버튼 두 개와 가운데 label을 묶은 hStackView에서 간격을 맞추기 위해 .fillEqually를 써줬다. 

    private lazy var hStackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [
            deleteButton,
            bookLabel,
            addButton
        ])
        stackView.axis = .horizontal // horizontal로 바꿀땐 기억해 axis
        stackView.distribution = .fillEqually
        return stackView
    }()

 

 

Fill Equally: 

StackView의 축을 따라 모든 View가 같은 크기로 채워지도록 해준다.

stackView의 fillEqually

 

 

addSubView로 만든 하위 계층을 layout func로 만든다. 이번에도 forEach를 사용했다.

hStackView snapkit을 활용해서 autoLayout 잡기.. 

 


 

| #4. UIStackView, UIScrollView @ VCs - ModalViewController

 

modal로 쑤~욱 올라올 이 화면은 stackView 세 개에..

scrollView를 넣고 그 안에 UILabel을 subView로 넣고.. 하다보니 코드가 꽤 길어졌다.  

 

 

vStackView나 hStackView나 공통적으로

arrangedSubviews를 해서 하위 요소들을 불러주어야 한다는 것과,

axis로 vertical인지 horizontal인지 명시하는 것을 기억해..

    lazy var vTopStackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [titleLabel, writterLabel])
        stackView.axis = .vertical
        return stackView
    }()

 

Dear. 세이노, 인간은 정말 변할 수 있나요..?

 

 

아직 버튼 쪽의 너비와 trailing이 깨지고 있는데,

이건 오늘 배운 UIStackView.Distribution과 spacing 등의 개념들을 사용해서 테스트하며 수정하면 될 것 같다. 

 

 

UIStackView.Distribution | Apple Developer Documentation

The layout that defines the size and position of the arranged views along the stack view’s axis.

developer.apple.com

 

 

spacing | Apple Developer Documentation

The distance in points between the adjacent edges of the stack view’s arranged views.

developer.apple.com

 

 

UIStackView.Distribution.fillEqually | Apple Developer Documentation

A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis.

developer.apple.com

 

 

어서 api를 연결해서 vc와 modal을 vc와 연동시키고 싶다. ..

 

to be continued.. 

'iOS 앱 개발자 프로젝트 > iOS 심화' 카테고리의 다른 글

[iOS] bookStore app project (4)  (0) 2024.05.09
[iOS] bookStore app project (3)  (4) 2024.05.08
[iOS] SnapKit (feat. SPM)  (2) 2024.05.05
[iOS] bookStore app project (1)  (2) 2024.05.04
[iOS] video playback app  (0) 2024.05.01