iOS/iOS 앱 개발 올인원 패키지 Online

[iOS] 패스트캠퍼스 챌린지 30일차 - UITableView(3)

듀IT 2021. 10. 5. 16:44

Custom Cell

우리가 원하는 대로 TableView Cell을 커스텀하는 것이다. 

먼저 CustomCell을 위한 class를 선언하고, UITableViewCell 프로토콜을 채택한다.

class ListCell: UITableViewCell {
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var bountyLabel: UILabel!
}

그리고 스토리보드에서 TableCell의 CustomClass를 해당 ListCell로 바꿔준다.

그리고 Object Library를 이용하여 Cell을 커스텀한다. 

 

import UIKit

class BountyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   
    let nameList = ["brook", "chopper", "franky", "luffy", "nami", "robin", "sanji", "zoro"]
    let bountyList = [30000, 50, 44440, 300000, 14000000, 50000, 300000, 20000]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    
    // UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bountyList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ListCell else {
            return UITableViewCell()
        }
        
        let img = UIImage(named: "\(nameList[indexPath.row]).jpg")
        cell.imgView.image = img
        cell.nameLabel.text = nameList[indexPath.row]
        cell.bountyLabel.text = "\(bountyList[indexPath.row])"
        return cell
    }
    
    
    //UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("--> \(indexPath.row)")
    }

}

class ListCell: UITableViewCell {
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var bountyLabel: UILabel!
}

해당 코드를 보면 tableView의 DataSource를 위한 Array를 선언하여 데이터를 만들어놓았다.

그리고 func tableView의 cellForRowAt 메소드는 Custom tableCell객체에 들어갈 데이터를 Set하고 있다. 

 

오늘의 공부 모습

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.