[英]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.