Forum Archive

How would I implement a delegate?

Brian

From what I understand, a delegate is a function that gets called whenever it's action occurs. I have my function, but it's not being called. Here's what I have:

class myclass():
ig=ui.load_view('myview')
tv=ig['textview1']

def textview_did_change(self, textview):
    print'hi'

How would I properly implement my delegate?

JadedTuna

@Brian, delegate is not a function, but a class.

Check this:

import ui, console

class Delegate:
    def textview_did_change(self, textview):
        console.hud_alert("textview_did_change!")

view = ui.View()
textview = ui.TextView()
textview.delegate = Delegate() # This is the line you are looking for
textview.flex = "WH"

view.add_subview(textview)
view.present("fullscreen")
Brian

@ShadowSlayer
Could you provide an example of how to do this while using ui.load_view()?
I can't seem to get it working.

JonB

In your example, you would use

tv.delegate=Delegate()

Where you implemented Shadow's Delegate class example.

JadedTuna

@Brian, read the docs :)

When you use ui.load_view(), it returns a ui.View object. In the UI editor you can select your textview element and set it's name to something like "mytextview". Then you can use textview = view["mytextview"].

Check this:

import ui
...
view = ui.load_view("uifile")
textview = view["mytextview"]
textview.delegate = Delegate()
...
Brian

When I append text to the text box, the delegate is not called even when I have it properly configured. Is this intentional or is it a bug? Also thanks for the help, much was learned.

JadedTuna

@Brian, do you mean my example? If you are talking about your code, could you please post it so I can take a look and maybe find out the problem?