I want to programmatically create a UITableView and the corresponding custom UITableViewCell in Swift. In the table view, it works fine, but it does not look like cell labels are created - they are returned as zero.
I also do not know how to refer to the size of the content presentation when sizing elements.
UITableViewCell
import UIKit
class BusUITableViewCell: UITableViewCell {
var routeNumber: UILabel!
var routeName: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
routeName = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
contentView.addSubview(routeNumber)
contentView.addSubview(routeName)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
UITableView delegate and source
import Foundation
import UIKit
class BusUITableView: NSObject, UITableViewDelegate, UITableViewDataSource {
var routeService: RouteService = RouteService()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var busRoutes: [Route] = routeService.retrieve()
return busRoutes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:BusUITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as BusUITableViewCell
var busRoutes: [Route] = routeService.retrieve()
cell.routeName.text = "test"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
View controller
mainTableView.registerClass(BusUITableViewCell.self, forCellReuseIdentifier: "cell")
source
share