Sorry, this has been done to death. By me also before. It's just about a small function (get_grid_rc) to create a grid to use with ui.Views. But its always worth bring up I think as there are always new users.
Grids can be represented/determined in many ways depending on your needs. I think the one I have done here is a pretty common need. Unfortunately the test code around the function sort obscures how simple it is. I am not saying this is the best way to do this btw. It's just a way. Again, to try and keep this simple, I did not deal with full screen. It's not thats its so difficult, but different ways to handle that case. Anyway, I hope someone finds it useful.
import ui
'''
get_grid_rc, can be a handy snippet to get a list of
ui.Rects for your view, given a width, height, num rows and num cols.
When doing ui stuff you often need this type of functionality.
I am sure its not the fastest in speed... Just want some small
function that does not eclipse your code.
w & h could be evaluated in the list comp, removing a line,
but thats seems like it would be a step too far
Also, get_grid_rc is not dealing with divide by zero errors.
Expects you pass valid params. eg. all params need to be non-zero (positive)!
While returning ui.Rects here, could easily change it to return a
list of ui.Buttons etc... However seems like a list of ui.Rects is
the best for an example.
As simple as this example is, it can be useful in many ways. eg. you
could call this in a custom views layout method to resize objects.
'''
def get_grid_rc(width, height, rows, cols):
'''
returns a single linear list of ui.Rects. l[0] will be the most top left
rect. l[-1] will be most bottom right rect.
'''
w, h = (width / cols, height / rows)
return [ui.Rect(w * j, h * i, w, h) for i, _ in enumerate(range(rows))
for j, _ in enumerate(range(cols))]
if __name__ == '__main__':
f = ui.Rect(0, 0, 320, 480)
v = ui.View(frame=f)
# simple test action callback for our ui.Buttons. All use this func.
def btn_action(sender):
print(sender.title)
# get the grid and use it as you like. I have used it to add ui.Buttons
# to a view. 6 rows x 7 columns for the size of the whole view.
# this is a normal grid to make month view on a calender
r_grid = get_grid_rc(v.frame.width, v.frame.height, 6, 7)
# iterate over the r_grid with enumerate. each iteration we get the index,
# and the ui.Rect.
for i, r in enumerate(r_grid):
btn = ui.Button(name=str(i), title=str(i),
bg_color='cornflowerblue', border_width=.5,
border_color='white', tint_color='black',
action=btn_action)
btn.frame = r
v.add_subview(btn)
v.present(style='sheet', animated=False)