Forum Archive

Text Field splits up word when entering into Table View

techteej

For some reason, entering text into a Text Field then adding to a table splits up the word into one cell for each letter.

# coding: utf-8

import ui

class Data (ui.ListDataSource):
    def __init__(self, items=None):
        ui.ListDataSource.__init__(self, items)

    def tableview_cell_for_row(self, tableview, section, row):
        cell = ui.TableViewCell()
        cell.text_label.text = str(self.items[row])
        return cell

def add_new_item(sender):
  tv1 = view['reminders']
  tv1.data_source = Data(items=view['new_item'].text)
  tv1.reload_data()

view = ui.load_view('reminders')
view.present('sheet')
omz

items is expected to be a sequence, commonly a list of strings, but a string itself is also a sequence, namely a sequence of characters. Add square brackets around the text:

#...
tv1.data_source = Data(items=[view['new_item'].text])
techteej

Thanks! How Would I get this to add to the list instead of overwriting it?

JonB

tv1.data_source.items.append
But, you would need to set up your datasource outside of your button action (to an empty list for example) when you init the view. Your button add new item method would append to the existing list.

techteej

@JonB could you demonstrate?

JonB

Demonstrating append below. Use of globals like this is not recommended (encapsulate into a class at least)

import ui
t=ui.TableView()
lst=ui.ListDataSource(items=['initial entry','another entry'])

def addrow(sender):
    t.data_source.items.append('you added this one')


t.data_source=lst
t.data_source.items.append('appended after creation ')
t.frame=(10,10,400,400)

b=ui.Button(frame=(450,50,100,100),bg_color='red')
b.title='clickme'
b.action=addrow

root=ui.View()
root.add_subview(t)
root.add_subview(b)
root.present()