iOS실무 5주차- 맛집 앱 개발(1) Table View

2025. 4. 3. 16:46iOS앱개발

 

상속과 프로토콜

 

Table View를 구현할 때  numberOfRowsInSection , cellForRowAt 메소드를 반드시 구현해야한다.

필수 구현은 아니지만 필요할 경우 해당 프로토콜의 메서드를 구현할 수 있다.

각 칸을 행(row) 셀 이 묶음을 섹션이라 한다

오늘은 UITableView와 UITableViewCell을 사용하여 테이블 뷰를 만들어보려 한다.

Table VIew Controller에는 Table VIew와 Table View Cell이 포함되어있다.

상하좌우의 제약 조건을 조절하여 해당 요소의 위치를 쉽게 잡을 수 있다.

1. 필요한 프로토콜을 채택한다

그러면 이런식으로 필수로 구현해야하는 2가지의 메서드때문에 에러가 발생하는데 이는 Fix를 누르면 자동으로 해당 메서드를 생성시켜준다

 

//
//  ViewController.swift
//  FoodB
//
//  Created by 컴소뉴맥 on 2025/04/03.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var table: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        table.dataSource = self
        table.delegate = self
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "myCell")
        cell.textLabel?.text = indexPath.description
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
}

기본 메서드와 섹션을 6개로 하여 간단히 구현한 소스이다.

 

위와같이 [1, 2]이러한 형태로 각각 [섹션, 행]의 순서로 표시된다.

  cell.imageView?.image = UIImage(named: "smile.png")

위와같은 코드를 통해 테이블셀에 이미지를 삽입할 수 있다.

 

맛집 앱 만들기

//
//  ViewController.swift
//  FoodB
//
//  Created by 컴소뉴맥 on 2025/04/03.
//

import UIKit
var storeName = ["1한식", "2분식", "3중식", "4학식", "5집밥"]
var foodImage = ["1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png"]

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var table: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        table.dataSource = self
        table.delegate = self
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "myCell")
        cell.textLabel?.text = storeName[indexPath.row]
        cell.detailTextLabel?.text = "\(indexPath.row)"
        cell.imageView?.image = UIImage(named: foodImage[indexPath.row])
        return cell
    }
    
   
    
}

정적 데이터를 추가하여 각 섹션에 반복적인 이미지, 이름이 뜨도록 하는 코드이다.

 

테이블뷰 셀(UITableViewCell)이란?

UITableViewCell은 UITableView에서 개별 행(Row)을 표시하는 UI 요소입니다.
즉, 테이블 뷰의 한 줄(행)을 구성하는 기본 단위라고 할 수 있습니다.

 

스토리보드에서 TableViewCell을 추가하고 이를 컨트롤하는

//
//  MyTableViewCell.swift
//  Food2
//
//  Created by 컴소뉴맥 on 2025/04/03.
//

import UIKit

class MyTableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

클래스를 추가한다.

또한 레이블에 대한 제약조건을 추가하여 레이아웃을 잡는다.
위 사진처럼 각각의 요소에 대해서 제약조건이 생긴것을 확인할 수 있다.

 

dequeueReusableCell(withIdentifier:) 자세한 설명

🔹 동작 원리

  1. UITableView는 화면에 보이는 셀만 생성(예: 5개 보임 → 5개만 생성).
  2. 스크롤할 때, 화면에서 사라진 셀을 재사용 큐(reuse queue)에 보관.
  3. 새로운 셀이 필요하면, 큐에서 기존 셀을 꺼내어 데이터만 변경 후 재사용.
  4. 새로운 셀을 만들지 않으므로 메모리 낭비를 줄이고 성능을 향상.

tableView(_:didSelectRowAt:) 설명

이 메서드는 사용자가 테이블 뷰의 특정 셀을 터치했을 때 호출되는 함수입니다.

 

추가적으로 이미지 아웃렛을 연결하여

//
//  MyTableViewCell.swift
//  Food2
//
//  Created by 컴소뉴맥 on 2025/04/03.
//

import UIKit

class MyTableViewCell: UITableViewCell {

    
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myImage: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

테이블뷰셀 메서드에 이미지 아웃렛에 UIImage타입으로 이미지를 넣어주면 된다.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "myCell")
        //        cell.textLabel?.text = storeName[indexPath.row]
        //        cell.detailTextLabel?.text = "\(indexPath.row)"
        //        cell.imageView?.image = UIImage(named: foodImage[indexPath.row])
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell
        cell.myLabel.text = indexPath.description
        cell.myImage.image = UIImage(named: foodImage[indexPath.row])
     
        

        return cell
    }

 

결과

'iOS앱개발' 카테고리의 다른 글

iOS실무 6주차  (0) 2025.04.10
iOS 실무 4주차  (0) 2025.03.27
iOS 실무 3주차  (0) 2025.03.20
iOS 실무 2주차  (0) 2025.03.13
iOS실무  (0) 2025.03.06