swift tableview code example
Example 1: swift scroll to tableviewcell
let indexPath = IndexPath(row: row, section: section)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
Example 2: swift table view needs
func setTableNeeds(){
tableView.delegate = self
tableView.dataSource = self
let nib = UINib(nibName: "cell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "cell")
}
extension NameOfUIViewController: UITableViewDelegate, UITableViewDataSource{
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) as! Cell
return cell
}
}
Example 3: write into table view swift 5
import UIKit
class ToDoListViewController: UITableViewController {
let itemArray = ["Study Swift", "Buy Eggs", "Read a newspapper"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoListCell", for: indexPath)
cell.textLabel?.text = itemArray[indexPath.row]
return cell
}
}