Forum Archive

Editable TextField on a TableView

mikael

I can place a TextField on top of the label in a TableView cell, but it will not get any touches.

Has anyone worked around this before?

I will share a code example soon.

cvp

@mikael Is not that what FormDialog does with its fields? Or I don't understand, sorry.

mikael

@cvp, thanks, form_dialog is certainly my fallback position for editing the items in the list, but ideally I could make the items editable directly on the list.

Here’s a minimal example, demonstrating the challenge - touches on the TextField, overlaid on the TableView row, are captured by the TableView.

import ui

data = ['a','b','c']

class MySource:

  def tableview_number_of_rows(self, tableview, section):
      return len(data)

  def tableview_cell_for_row(self, tableview, section, row):
      cell = ui.TableViewCell()
      cell.text_label.text = '-'*100
      v = ui.TextField(text=data[row],
        background_color='white',
        bordered=False,
        frame=cell.text_label.bounds,
        flex='WH')
      cell.text_label.add_subview(v)
      return cell

table = ui.TableView(data_source=MySource())
table.present()

Thanks.

cvp

@mikael try something like

        frame=(0,0,50,30),#cell.text_label.bounds,
        flex='WH')
      #cell.text_label.add_subview(v)
      cell.content_view.add_subview(v)
mikael

@cvp, thanks! Using the content_view together with row_height gives me all the power of TableView with custom, in-place-editable text fields.

cvp

@mikael 👍

mikael

Funky - adding view x as a subview of cell.content_view works, but for some reason the superview of x is not set.

cvp

@mikael Are you sure that, when you get superview, it is still active?
If you create it during cell_for_row, it is only active when displayed

If you only want to know for which row, store a user attribute to you TextField,
Like v.row = row

mikael

@cvp, I do not know if it is about activation, as this is within the cell creation method of the data source, not later. Here’s what I ended up doing:

  • cell.content_view
  • container
    • textfield

With the additional container view matching the content_view size, my textfields have a superview, otherwise not. I need the superview for my docking constraints to work – which is probably a rare use case, and thus the missing superview is rarely a problem.

cvp

@mikael ok, understood