본문 바로가기

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

[iOS] bookStore app project (4)

api 통신에 성공한 지난 글에 이어,

 

통신 결과 값(success or failure)을 담을 배열을 생성하여 switch문을 통해 담아내고,  ←  #1

검색결과 cell을 만들었던 tableView에  ←  #2

UITableViewDataSource 프로토콜 채택 ←  #3

func(numberOfRowsInSection, cellForeRowAt) 바인딩  ←  #4 

 

7r보ㅈr Z...  •̤᷆ ₃ •̤᷇ ฅ 


| #1.  api 통신 결과 값을 담을 데이터 배열 생성

 

Document 타입의 데이터를 담을 배열을 생성

var answerList = [Document]()  // 데이터를 담을 배열 생성

 

 

사용자의 검색어를 기반으로 네트워크 요청을 수행하고, 그 결과를 테이블 뷰에 표시하는 기능을 구현

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let text = searchBar.text {  // 검색어 가져오기
            
    //      네트워크 요청 및 데이터 처리:
            networkManager.fetchRequest(title: text) { result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let yeon): // Model: Document
    //                    print(yeon.documents)
                        self.answerList = yeon.documents // api 호출이 성공했을 경우 answerList에 데이터를 담는다.
                        self.resultTable.reloadData() // reload를 해서 TableView에 노출
                      //  print(self.answerList)
                    case.failure(let error):
                        print(error)
                    }
                }
            }
        }
        // print(searchBar.text)
    }

 

vc의 answerList →  UISearchBarDelegate를 상속받는 vc extension에서 데이터를 담는다.

 

두 변수는 반드시 동일한 타입[Document]을 가져야 한다.

 

 

 

 

| #2. SearchResultTableVIewCell 생성 + 구현

 

fistVC의 UITableView에 들어갈 SearchResultTableVIewCell을 구현한다.

SearchResultTableViewCell 생성

 

SearchResultTableCell component 변수 및 layout 설정 / 초기화 / 함수 호출

 

 

 

| #3. UITableViewDelegate,  UITableViewDataSource 

 

UITableViewDelegate와 UITableViewDataSource 프로토콜을 채택하고,

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableSetup() {
        resultTable.delegate = self
        resultTable.dataSource = self
    }

 

 

tableSetup() 메서드에서 테이블 뷰의 delegate와 dataSource를 self로 설정한다.

 

tableSetup() 메서드: 이 메서드에서 테이블 뷰의 delegate와 dataSource를 self로 설정하고, 이를 통해 ViewController 클래스가 테이블 뷰의 delegate와 dataSource 역할을 수행할 수 있게 해준다.

 

 

 

| #4. func(numberOfRowsInSection, cellForeRowAt) 바인딩

 

numberOfRowsInSection(_:) 메서드는 테이블 뷰에 표시할 행의 개수를 알려주고,

cellForRowAt(_:) 메서드는 각 행에 표시할 셀을 구성한다.

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return answerList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = resultTable.dequeueReusableCell(withIdentifier: "SearchResultTableViewCell", for: indexPath) as? SearchResultTableViewCell else { return UITableViewCell() }
        
        // answerList 주입 대작전
        let item = answerList[indexPath.row]
        print(item)
        // 주입 시작
        cell.titleLabel.text = item.title
        cell.authorLabel.text = item.authors.joined() // joined : 배열을 한번에 보여주겠다. 즉, 배열의 전체 값을 문자열로 변환
        cell.priceLabel.text = item.price.stringValue // 형 변환의 stylish한 버전
        return cell
    }

 

  

 

To be continued.. 

 

 

 

동일한 메소드를 사용했던 과거 소환 ▽

https://maggie-chae.tistory.com/137

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

[iOS] bookStore app project (5)  (6) 2024.05.12
[iOS] bookStore app project (3)  (4) 2024.05.08
[iOS] bookStore app project (2)  (2) 2024.05.07
[iOS] SnapKit (feat. SPM)  (2) 2024.05.05
[iOS] bookStore app project (1)  (2) 2024.05.04