Swift/UIKit
[UIkit] Tableview 코드로 만들기
by 마라민초닭발로제
2023. 3. 21.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// TableView 생성 및 Delegate, DataSource 설정
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
// TableView Cell 등록
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// TableView를 View에 추가
view.addSubview(tableView)
}
// TableView 데이터 소스
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10 // 데이터 수 설정
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row + 1)"
return cell
}
// TableView Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row + 1) selected")
}
}