class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var placeAddrLabel: UILabel!
@IBOutlet weak var placeNameLabel: UILabel!
@IBOutlet weak var placeDistance: UILabel?
}
class MapTableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.reloadData()
}
}
delegate
와 datasource
는 protocol을 통해 구현되어 있고, self
를 통해서 채택하는 과정이 필요하다. 가끔 다 구현해놓고 테이블뷰가 안보인다면 이 두 프로토콜을 채택하는 코드가 빠져있는 경우가 있을수도...아래는 위 두 프로토콜이 실제로 구현되는 방식이다.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allMarkers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
let marker = allMarkers[indexPath.row]
cell.placeNameLabel.text = marker.placeName
cell.placeAddrLabel.text = marker.address
return cell
}
numberOfRowsInSection
함수는 tableView에 사용되는 cell의 숫자를 전달한다.dequeueReusableCell
함수를 사용해, 만들어놓은 cell 클래스를 사용할 수 있다.withIdentifier
에 해당하는 cell을 통해 tableView의 데이터를 전달한다.DataSource가 테이블 뷰의 row에 몇 개의 cell이 들어가야하는지, 각각의 섹션에 따라서 indexPath에 따른 데이터들을 어떤 방식으로 보여줄지를 정의했다면, delegate 메서드는 사용자와의 interaction에 관련된 내용을 정의한다.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let marker = allMarkers[indexPath.row]
if let url = URL(string: marker.placeUrl ?? "") {
let safariVC = SFSafariViewController(url: url)
self.present(safariVC, animated: true, completion: nil)
}
self.tableView.reloadData()
}
didSelectRowAt
함수에서는 사용자가 인터렉션을 통해 가져온 indexPath에 따라 cell 항목을 식별하고 처리할 수 있다.*삭제 기능에 대한 글 추가 예정
깔끔한 정리 잘보고 갑니다!! 아 그래서 소주 지도는 언제 출시한다고요,,?