This is a pattern I've been using to instantiate custom Views that have accompanying pyui files with dynamic data. Just looking for some feedback or any constructive criticism to improve it or maybe just share the pattern if it can help someone else.
Let's say I have a custom ui.View class called MyView. The pyui file that represents this View would be called my_view.pyui, and would set Custom Class to MyView in the main view properties. This view would contain a single Label component named lbl. I want to be able to instantiate this view with a constructor-like method that affects the contents of the View when it gets shown.
The following pattern has made this possible in my_view.py:
# my_view.py
import ui
class MyView(ui.View):
def did_load(self):
self.my_lbl = self['lbl']
def init(self, text):
'''
since the ui.load_view() handles instantiating the actual View object, we can't access the true __init__
method. So we'll call this one as part of our custom static load_view method.'''
self.my_lbl.text = text
@staticmethod
def load_view(text):
'''
I particularly like this simple shortcut as it allows me to create instances of a custom class somewhere
else without having to remember the name of its file. Much cleaner.
This becomes our makeshift "constructor."'''
v = ui.load_view()
v.init(text)
return v
if __name__ == '__main__':
# load MyView and initialize the view's label with text "Hello World!", then show the view.
v = MyView.load_view("Hello World!")
v.present()
That wysiwyg UI editor in Pythonista is so stinkin' handy, and this pattern seems like a nice compromise between using the UI editor, and being able to create dynamic, flexible, and reusable views in a pythonic way.
