Skip to content

The First Responder: Put a Cursor in a Text Field

One thing you might want to do in an application is to set the cursor to be active in (to blink in) a text field of your choosing. This is done through the “first responder” property which can be set for windows in your application. I have had a lot of trouble with this. I haven’t had a lot of success in making something useful out of reading the property, even though you can set it. If you have a reference to your window in the variable “myWindow” then you could set the cursor to be active in a field called “secondField” with a line of code like this:

set the first responder of myWindow to text field "secondField" of myWindow

You can download a very simple sample application which shows you how you can respond to the “return” key to move to the next text field. It also has some code to show you a button that, when pressed, will move the first responder to the second field on the screen.

Download the sample XCode project here: First Responder Example

Here is are the key lines of code involved:

on clicked theObject
	if the name of theObject is "switchField" then
		set myWindow to the window of theObject
		set the first responder of myWindow ¬
           to text field "secondField" of myWindow
	end if
end clicked

on keyboard up theObject event theEvent
	set myWindow to the window of theObject
	if the name of theObject is "firstField" then
		if the character of theEvent is return then
			set the first responder of myWindow to ¬
                text field "secondField" of myWindow
		end if
	else if the name of theObject is "secondField" then
		if the character of theEvent is return then
			set the first responder of myWindow to ¬
                 text field "firstField" of myWindow
		end if
	end if
end keyboard up