Skip to content

Set Focus to a Field Using an iOS Declare

You can call into Cocoa Touch APIs to use methods and properties that are not built into the framework by using the Declare command. To create a Declare statement you first need to track down the API you want to use in Apple’s documentation: Apple Developer Documentation. Most of the time you will reference the Foundation and UIKit libraries, but there are many other libraries as well. Xojo Declares use the Objective-C names so be sure to refer to those in the documentation rather than the Swift naming.

When you call Cocoa methods you supply the method name using the Selector part of the Declare command. The selector name has to end in a “:” if there are any parameters that are passed, an oddity of how Objective-C works. Unlike with Xojo methods, the case of the name also has to match exactly. For the Xojo Declare, the first parameter is always required and must be a reference to the class containing the method you are calling.

To start with a simple example, consider that you may want to set focus to a text control such as an iOSTextField. Xojo does not provide a method for this. Looking at the Summary on the iOSTextField page you’ll see that the actual UIKit control is called “UITextField”. Click the link to open the Apple doc page. On the doc page you’ll find information about calling becomeFirstResponder to show the keyboard, which is what happens when a text field gets focus. When you click on becomeFirstResponder you’ll get to its doc page with this declaration:


The above is Objective-C code that indicates that this is a function that returns a Boolean value. You should also note on the page that this is part of the UIKit library. With this information you can now create a Xojo Declare command to call it:

Declare Function becomeFirstResponder Lib "UIKit" Selector "becomeFirstResponder" (controlHandle As Ptr) As Boolean

The important thing to note here is that you have to always have a parameter (the first parameter) that is a reference to an instance of the class (or control in this case).

You can call this method just as you would any other Xojo method, but remember you have to pass it a reference to the control. Assuming you have a control called TextField1 on the view you can call the method like this:

Call becomeFirstResponder(TextField1.Handle)

The Call command is used to ignore the return value, which is not relevant in this situation.

If you want to use this function often you can wrap it in an Extension method so that it is available everywhere. To do this, create a module and add a global method to it with this declaration:

SetFocus(Extends c As iOSTextField) As Boolean

To the method, add the Declare code as follows:

Declare Function becomeFirstResponder Lib "UIKit" Selector "becomeFirstResponder" (controlHandle As Ptr) As Boolean
Return becomeFirstResponder(c.Handle)

Now you can call the method like this:

Call TextField1.SetFocus

For more information: