Create UITableView programmatically in Swift
ios, swift, uitableview
Solution
Note: As you mentioned you just started programming in `Swift`. I created a tableView programmatically. `Copy` and `paste` below code into your `viewController` and run the project...
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let myArray: NSArray = ["First","Second","Third"]
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
}
Output:
Problem
I try to implement UITableView programmatically without use of xib or Storyboards. This is my code: ViewController.swift ``` import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let table: UITableViewController = MyTableViewController() let tableView: UITableView = UITableView() tableView.frame = CGRect(x: 10, y: 10, width: 100, height: 500) tableView.dataSource = table tableView.delegate = table self.view.addSubview(tableView) } } ``` MyTableViewController.swift ``` import UIKit class MyTableViewController: UITableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { NSLog("sections") return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { NSLog("rows") return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { NSLog("get cell") let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell") cell.textLabel!.text = "foo" return cell } } ``` But when I run app, all I get is empty table. In log I see a few lines of `sections` and `rows`, but no `get cell`. How can I fix this code to get table with 6 lines of `foo` text?