I am sure I have done this type of tip before. But as time passes on and new users join they get old. This is only for people who don't know about ui.Rect. There is a small problem with ui.Rect. It's not documented as a ui.Rect. It's actually documented as - class scene.Rect(x, y, w, h). Also the autocomplete in the editor does not recognise ui.Rect. Anyway ui.Rect and scene.Rect are the same. Regardless, ui.Rect is recognised by the interpreter.
So why is it important to know about it? Firstly , attrs in ui.View like frame and bounds are ui.Rects. They can be assigned a tuple or a ui.Rect, omz takes care of that. But it's the methods you can use on ui.Rects that makes it worth knowing about. It's not rocket science stuff, but can save you a lot of time and reduce bugs. There is a link to the documentation below. But it can really help reduce your code and simplify things.
I have posted below an example of adding variable height views to a scrollview. Maybe the code is not as tight as I could be, but you can see it's pretty simple. Granted, you can do the same thing doing the calls yourself, but there is a lot of help built in already.
Again, this is only useful if you are unaware of ui.Rect/scene.Rect
Hope it's useful for someone
The sample code below should be size and orientation friendly
# Pythonista Forum - @Phuket2
import ui, editor
class MyClass(ui.View):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sv = None
self.v_gap = 10 # vertical space between views
self.make_view()
def make_view(self):
sv = ui.ScrollView(frame = self.bounds.inset(20, 20))
sv.flex = 'wh'
sv.bg_color = 'white'
sv.corner_radius = 3
self.sv = sv
self.add_subview(sv)
def add_view(self, h):
parent = self.sv # our parent is the ScrollView
r = ui.Rect(0, 0, parent.width, h).inset(5, 5)
v = ui.View(frame = r)
v.y = self.calc_y()
v.border_width = 1
v.corner_radius = 6
v.flex = 'w'
parent.add_subview(v)
parent.content_size = (0, v.frame.max_y + self.v_gap )
def calc_y(self):
# returns the new y for the next element that will be added to
# scrollview.
# seems stupid to do this. i am tending more to do this style
# now. have a var that points to our parent contextually.
# i make less mistakes this way, and think faster
parent = self.sv # our parent is the ScrollView
if not len(parent.subviews):
return self.v_gap
return parent.subviews[len(parent.subviews)-1].frame.max_y + self.v_gap
if __name__ == '__main__':
_use_theme = True
w, h = 600, 800
w, h = 320, 568 # iphone 5 up
f = (0, 0, w, h)
style = 'sheet'
animated = False
mc = MyClass(frame=f, bg_color='white', name = 'ScrollView Test')
if not _use_theme:
mc.present(style=style, animated=animated)
else:
editor.present_themed(mc, theme_name='Oceanic', style=style, animated=animated)
# its just an example... we do the call to create the scrollview
# views here.
h_list = [100, 200, 50, 100, 60, 80, 90, 300, 44, 60, 90, 300, 90]
for h in h_list:
mc.add_view(h)