[英]Create auto-complete TextField in Pythonista 3
可以使用TableView在Pythonista中创建一个下拉列表。 TableView实际上只是单列列表,它们不仅仅用于表。
因此,步骤将是:
您可以通过将其.hidden
属性设置为True
来隐藏任何视图。
您可以通过创建实现textfield_did_change
的委托对象来在TextField中键入开始时执行操作。
通过为TableView提供data_source
(可能是ui.ListDataSource
的实现),可以将TableView设置为具有项目列表。 每当数据源上的items
属性更改时,选项列表也会自动更改。
您可以对用户从TableView中选择一个选项做出反应,方法是对TableView的delegate
设置一个action
。
TableView,TextField,ListDataSource,委托和操作的文档可以在Pythonista的iOS本机GUI中找到。
这是一个基本示例:
# documentation at http://omz-software.com/pythonista/docs/ios/ui.html
import ui
# the phoneField delegate will respond whenever there is typing
# the delegate object will combine phoneField delegate, tableview delegate, and data source, so that it can share data
class AutoCompleter(ui.ListDataSource):
def textfield_did_change(self, textfield):
dropDown.hidden = False
# an arbitrary list of autocomplete options
# you will have a function that creates this list
options = [textfield.text + x for x in textfield.text]
# setting the items property automatically updates the list
self.items = options
# size the dropdown for up to five options
dropDown.height = min(dropDown.row_height * len(options), 5*dropDown.row_height)
def textfield_did_end_editing(self, textfield):
#done editing, so hide and clear the dropdown
dropDown.hidden = True
self.items = []
# this is also where you might act on the entered data
pass
def optionWasSelected(self, sender):
phoneField.text = self.items[self.selected_row]
phoneField.end_editing()
autocompleter = AutoCompleter(items=[])
autocompleter.action = autocompleter.optionWasSelected
# a TextField for phone number input
phoneField = ui.TextField()
phoneField.delegate = autocompleter
phoneField.keyboard_type = ui.KEYBOARD_PHONE_PAD
phoneField.clear_button_mode = 'while_editing'
# the drop-down menu is basically a list of items, which in Pythonista is a TableView
dropDown = ui.TableView()
dropDown.delegate = autocompleter
dropDown.data_source = autocompleter
# hide the dropdown until typing starts
dropDown.hidden = True
# create interface
mainView = ui.View()
mainView.add_subview(phoneField)
mainView.add_subview(dropDown)
# present the interface before aligning fields, so as to have the window size available
mainView.present()
# center text field
phoneField.width = mainView.width*.67
phoneField.height = 40
phoneField.x = mainView.width/2 - phoneField.width/2
phoneField.y = mainView.height/3 - phoneField.height/2
# align the dropdown with the phoneField
dropDown.x = phoneField.x
dropDown.y = phoneField.y + phoneField.height
dropDown.width = phoneField.width
dropDown.row_height = phoneField.height
在我的iPhone上,此代码创建一个界面,如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.