0

I have a custom cell (CustomCell.swift) and I would like to have a reference to the parent table which contains that cell. (TableView.swift)

How can I do it?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
nethuszar
  • 225
  • 3
  • 13
  • What are you looking to do with this reference? You could create a delegate in your CustomCell and have TableView conform to that delegate. – chickenparm Jul 18 '16 at 17:22
  • Can you please write me a detailed answer how I can implement this? – nethuszar Jul 18 '16 at 17:23
  • I might have time later today. Google swift delegation example for some help now. Here is what I found from googling: https://gist.github.com/austinzheng/db58036c4eb825e63e88 – chickenparm Jul 18 '16 at 17:24
  • 1
    Why does your cell need to know about its table view? It should not need to know. – rmaddy Jul 18 '16 at 17:26
  • Because when I click a button in the cell I would like to resize that cell to set a bigger height and display a hidden textfield. – nethuszar Jul 18 '16 at 17:28
  • For that purpose you need only the index path. To change the height of the cell implement `heightForRowAtIndexPath`, change the model and reload the index path. – vadian Jul 18 '16 at 17:32
  • But how can I get the IndexPath of a cell? The table is populated from a database. – nethuszar Jul 18 '16 at 17:33
  • You are going about this all wrong. Your cell class should provide a delegate protocol. When the button is pressed, the cell should tell its delegate that its state has changed. That's al the cell should do. Now you make the table view controller the cell's delegate. The controller implements the cell's delegate protocol method(s). The implementation should simply reload that cell and based on the cell's state, you set its height and content. – rmaddy Jul 18 '16 at 17:41
  • Whatever logic you are using here, think about moving it from your Cell class to your TableView class. The table view should be the data source and controller of your cells, not the other way around. If your cells need to know about the table view they are used in, that may be a sign of bad structural design. – return true Jul 18 '16 at 17:43

0 Answers0