native.newTextField()

Type Function
Library native.*
Return value TextField
Revision Release 2024.3703
Keywords text input, text fields, native text
See also native.newTextBox()
native.setKeyboardFocus()
object.inputType
userInput

Overview

Creates a single-line TextField object for text input. For multi-line text input, see native.newTextBox().

The default font size of the text field depends on the field’s height and is calculated to be the maximum font size that will fit inside the field, taking into account such things as platform-specific margins. The easiest way to create a text field is to set its height and let the font size be calculated automatically — however, note the first “gotcha” below.

Native text fields can listen for userInput events (see example).

Native text fields can display optional placeholder text (nil by default). This can provide a “hint” as to what the user should enter in the field. If set, the placeholder string is displayed using the same style information (except the text color). The placeholder does not appear once actual text has been input into the field and it does not currently participate in determining the size of the text field.

Gotchas

Syntax

native.newTextField( x, y, width, height )
x (required)

Number. The x coordinate that corresponds to the center of the text field.

y (required)

Number. The y coordinate that corresponds to the center of the text field.

width (required)

Number. Width of the text field.

height (required)

Number. Height of the text field.

Properties / Methods

See the TextField documentation for a list of methods and properties.

Events

See the userInput event documentation for properties related to various TextField object events.

Examples

Standard
local defaultField

local function textListener( event )

    if ( event.phase == "began" ) then
        -- User begins editing "defaultField"

    elseif ( event.phase == "ended" or event.phase == "submitted" ) then
        -- Output resulting text from "defaultField"
        print( event.target.text )

    elseif ( event.phase == "editing" ) then
        print( event.newCharacters )
        print( event.oldText )
        print( event.startPosition )
        print( event.text )
    end
end

-- Create text field
defaultField = native.newTextField( 150, 150, 180, 30 )
defaultField:addEventListener( "userInput", textListener )
Numeric Input Only
local numericField

local function textListener( event )

    if ( event.phase == "began" ) then
        -- User begins editing "numericField"
    end
end

-- Create text field
numericField = native.newTextField( 150, 150, 180, 30 )
numericField.inputType = "number"
numericField:addEventListener( "userInput", textListener )