button action not called when view is added to native view
I added a pythonista ui view as a subview to an underlying native view.
Displaying labels and buttons is working fine. So I assume that I made no big error here.
Where my problem starts, is when I try to wire the button actions to methods in my view code.
I did it certainly the wrong way because the action delegates of the buttons are simply not called.
Here is my progress so far. Has anybody an idea how to connect the button action to methods in pythonista code?
from objc_util import * import ui WKWebView = ObjCClass('WKWebView') UIViewController = ObjCClass('UIViewController') def btnclicked(sender): print('btnclicked') @on_main_thread def main(): rootVC = UIApplication.sharedApplication().keyWindow().rootViewController() tabVC = rootVC.detailViewController() CustomViewController = create_objc_class('CustomViewController', UIViewController, methods=, protocols=) vc = CustomViewController.new().autorelease() vc.title = 'View Test' vc.navigationItem().rightBarButtonItems =  webView = WKWebView.new().autorelease() vc.view = webView tabVC.addTabWithViewController_(vc) v = ui.View() v.name = 'View Test' v.width = 600 v.height = 300 v.background_color = 'red' button = ui.Button(title='ok') button.center = (v.width * 0.5,v.height * 0.5) button.flex = 'LRTB' button.action = btnclicked v.add_subview(button) webView.addSubview_(v) if __name__ == '__main__': main()
PS: using a pythonista ui view instead of a native view as a super view is working as expected. (e.g. buttons delegates are called) So I assume it has something to do with the native view.
Guessing that your
buttonis collected. Try to add
webView.addSubview_(v). Should fix it.
Out of curiosity, why do you feel you need a custom view controller/view? I guess so you can add a tab to the editor instead of presenting in the panel tab?
In this case the issue is that v and button are getting gc'd on the python side, since you don't store a reference to them. When I run your code, pressing the button gives a segmentation fault, which is usually a good indication you are accessing an object that no longer exists.
retain_global(v)will do the trick here.
Thank you so much for replying that fast. The btnclicked get called when using retain_global.
In fact the posted code is only the isolation of the button not clicked problem in my „hybrid“ app. For the settings panel of my app I would like to use pythonistas ui package, because I like to do it with pythonistas ui designer.
I guess my point is that you could have a root ui.view, then add a WKWebView as a subview, without needing a custom view controller at the top: I.e
root=ui.View() root.objc_instance.addSubview_(w) root.present('panel')
(You might need to present before adding the subview)
Either way works, ultimately -- having the top view be a pythonista UI.View lets it play nicer with pythonista and other views. If you want to present to the editor tab, your approach is best.