0

at the moment I have a UITableView where the user can add cells that have a textLabel inside of it.

That is how I set the label:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath)
    let currentWish = self.wishList[indexPath.row]
    cell.textLabel?.text = currentWish.wishName
    cell.backgroundColor = .clear

    return cell
}

My question is, how I can custom textLabel (font, constraints,...). I tried creating a custom UILabel inside my WishCell class but I can not access it in cellforRowAt with cell.theLabel.

I hope you understand my problem, I am very grateful for every help :)

SOLVED

I just forgot the as! WhishCell in cellForRowAt. Thanks for all your help :)

  • yes, I am doing that. But my problem is that I need to custom `textLabel` and I don't know how –  Nov 26 '19 at 18:57
  • Possible duplicate of [Custom UITableViewCell programmatically using Swift](https://stackoverflow.com/questions/25413239/custom-uitableviewcell-programmatically-using-swift) – koen Nov 26 '19 at 19:04

2 Answers2

0

You need to cast to you cell custom class name

let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as! CellName
cell.lbl.text = ////

 class CellName:UITableViewCell {
    let lbl = UILabel() 
   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
       lbl.backgroundColor = UIColor.red
       self.contentView.addSubview(lbl)
       // set constraints here 
    }

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }
 }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • you can change the font but not constraints , you need to do this with `lbl` in your custom cell – Shehata Gamal Nov 26 '19 at 18:59
  • any way I can create a `customLabel` inside my `Class WhishCell` so I can call `cell.customLabel.text = currentWish.wishName` inside `cellForRowAt`? –  Nov 26 '19 at 19:04
  • aaah I was just an idiot... I missed the `as! WhishCell` ! Thanks man :D –  Nov 26 '19 at 19:17
0

Dont force un-wrap it.. try using guard or if let

guard let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as? WhishCell else{
  return UITableViewCell()
}
cell.lbl.text = "my text" 
let currentWish = self.wishList[indexPath.row]
cell.textLabel?.text = currentWish.wishName
cell.backgroundColor = .clear

return cell
Mithra Singam
  • 1,905
  • 20
  • 26