Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Set TableView scroll position?
-
Does anyone have code which successfully sets the scroll position of a TableView? I'm trying to scroll the table to a specific item, and I have what ought to be the correct y-offset, but when I try to set:
mytable.content_offset = (0, y)
the content doesn't change position.
The docs say that table views inherit from scroll views, so they should have all the same methods...so I feel like I'm doing something wrong here.
In a related question: is there a good way to get the position of a particular table view item/index in the tableview's coordinates? Right now I'm just multiplying the row_height by the item index, but that's not great if I were ever to have variable item heights, or section headers or anything of that sort.
-
@shinyformica, the following works. Setting
content_offset
beforepresent
does not - offset is set, but gets set again back to (0,0).Hope this helps.
#coding: utf-8 from ui import * import editor ''' Dummy lines to have something to scroll to ''' l = ListDataSource(editor.get_text().splitlines()) v = TableView() v.data_source = l v.background_color = 'white' v.present() v.content_offset = (0,100)
-
@shinyformica, for the exact location you probably need ObjC, see here.
-
@shinyformica you could try this but I did a quick test in form_dialog but it returns 0,0.
I'm sorry but I don't understand why 😢from objc_util import * import ui def xyCell(tableview,section,row): tvo = ObjCInstance(tableview) NSIndexPath = ObjCClass('NSIndexPath') i = NSIndexPath.indexPathForRow_inSection_(row,section) # indexPath r = tvo.rectForRowAtIndexPath_(i) # CGRect x = r.origin.x y = r.origin.y return x,y
-
You may want to try on_main_thread.
-
Yes, and perhaps wait a little delay after the present, what I didn't do
-
The wait is sufficient...I used ui.delay(...,0.2)
-
Thanks all, as usual!
The wait for the table view to become valid can be very short, as short as 0.01 seconds, apparently. Unfortunately there's no simple way to be notified when a UIView becomes visible (anyone have a generic notification-y way of doing that?), and even then I don't know that just being visible for a table view is the same as it having valid rows/indices.
Also, to scroll to a specific row turns out to be very easy, once you have a table view with valid indexes displayed:
UITableViewScrollPositionMiddle = 2 tvobjc = self.tableview.objc_instance NSIndexPath = objc_util.ObjCClass("NSIndexPath") nsindex = NSIndexPath.indexPathForRow_inSection_(index,0) tvobjc.scrollToRowAtIndexPath_atScrollPosition_animated_(nsindex, UITableViewScrollPositionMiddle, True)
Works great, set that last parameter to False to scroll without animation.