Custom UITableViewCell in Swift programmatically

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()
        // Initialization code
        routeName = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) // not sure how to refer to the cell size here

        contentView.addSubview(routeNumber)
        contentView.addSubview(routeName)
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

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"  // test string doesn't work, returns nil
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


    }

}

View controller

    mainTableView.registerClass(BusUITableViewCell.self, forCellReuseIdentifier: "cell")
+4
source share
2 answers

If you are not attached to the prototype cell in the storyboard, you need to register the class for your cell against your tableView using registerClass(_ cellClass: AnyClass, forCellReuseIdentifier identifier: String)

In your case you will use something like this

  tableview.register(BusUITableViewCell.self, forCellReuseIdentifier:"cell")

, NIB awakeFromNib .

:.registerClass() .register()

+4

, "" ( nib), awakeFromNib() . , . ... (, ) .

0

Source: https://habr.com/ru/post/1569769/


All Articles