본문 바로가기

iOS UI

[UITableView]

공식문서 바로가기

 

1. storyboard에서 tableView 추가

2. UITableViewCell 만들기

 

 

3. TableViewCell 연결

 

nib을 register해야한다. UITableViewController.swift 파일의 viewDidLoad()에 작성했다.

let nibName = UINib(nibName: "StudentCell", bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: "StudentCell")

4. UITableViewController.swift와 연결

 

5. 보여줄 데이터 생성하기

struct Student {
    let name: String
    let id: String
}

 

var studentList: [Student] = []

 

studentList.append(Student(name: "A", id: "A1001000"))
studentList.append(Student(name: "B", id: "A2039928"))
studentList.append(Student(name: "C", id: "B938r989"))

 

6. number in section, return UITableViewCell 함수 만들기

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return studentList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "StudentCell", for: indexPath) as? StudentCell else { return UITableViewCell() }
        
        let student = studentList[indexPath.row]
        
        print("\(student.name), \(student.id)")
        
        cell.nameLabel?.text = student.name
        cell.idLabel?.text = student.id
        
        
        return cell
    }