I create a table view programmatically, and custom its cell

in TheCell.swift

import Foundation
import UIKit

class TheCell: UITableViewCell {
  var takeTime: UILabel = UILabel()

  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.backgroundColor = .clear

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

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

  override func layoutSubviews() {
    takeTime = UILabel(frame: CGRect(x:0, y:0, width:100,height:40))
    takeTime.textColor = .lightGray

and in table view, I use

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? TheCell
    if (cell == nil) {
        cell = TheCell(style: .default, reuseIdentifier: "cell")
    cell?.takeTime.text = "23:23"
    return cell!

I thought I can get a list of time 23:23, but there's nothing, any ideas?

1 Answers

Alastar On Best Solutions

instead of adding takeTime as a cell subview like this: self.addSubview(takeTime) add it as a subview of the cell contentView: contentView.addSubview(takeTime)

Also, in layoutSubviews just set frame of the label: takeTime.frame = CGRect(x:0, y:0, width:100,height:40)