import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK:- Sample Data Array to load in TableView
let sampleArrray: \[String\] = \["val1", "val2", "val3", "val4", "val5"]
//MARK:- Cell reuse identifier
let cellReuseIdentifier = "cell"
//MARK:- UITableView outlet
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Registering the custom cell
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// Setting delegate and Datasourse as same viewcontroller (this code is not neccessory if we are setting it from storyboard)
tableView.delegate = self
tableView.dataSource = self
}
//UITableview required methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sampleArrray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = sampleArrray\[indexPath.row\]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("clicked at: \(indexPath.row)")
//Here u can get the selected cell and add action related to this cell seelction
}
Added Screenshot for setting Datasource and delegate from storyboard
solved How to load Custom cell (Xib) in UITableview using Swift