TextBox

Mostrar obsoleto

*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.

Un TextBox permite al jugador proporcionar una entrada de texto.Se comporta de manera similar a un TextButton , excepto que un solo TextBox se puede poner en el foco al hacer clic, tocar o seleccionar con el gamepad.Mientras está en foco, el jugador puede usar un teclado para cambiar la propiedad Text .

  • Si no hay texto, el PlaceholderText será visible. Esto es útil al solicitar a los jugadores del tipo o formato de datos que deben ingresar.
  • Por defecto, la propiedad ClearTextOnFocus está habilitada y garantiza que no haya texto existente cuando se enfoca un TextBox.Esto puede no ser deseable para el texto que debe ser editable por el jugador.
  • La propiedad MultiLine permite a los jugadores ingresar múltiples líneas de texto con caracteres de nuevo párrafo ( \n ).

El ContextActionService honra las teclas de las cajas de texto y evitará automáticamente que se pasen eventos de presión de tecla a acciones vinculadas con ContextActionService:BindAction().UserInputService.InputBegan y eventos relacionados seguirán disparándose mientras una caja de texto esté en foco.

Estado de enfoque

Es posible detectar y cambiar el estado de enfoque de un TextBox:

  • Puedes usar CaptureFocus cuando aparece un diálogo para que el jugador no tenga que hacer clic en un TextBox cuando esté disponible; puedes usar ContextActionService:BindAction() para vincular una cierta tecla para enfocar un TextBox usando esta función.Cuando un TextBox entra en foco, se activa el evento Focused.
  • Puedes detectar si un cierto TextBox está en el enfoque usando IsFocused . Alternativamente, UserInputService:GetFocusedTextBox() se puede usar para verificar si algún TextBox está en el enfoque.
  • Cuando el jugador termina de introducir texto, se activa el evento FocusLost que indica si el usuario presionó Enter para enviar texto junto con el InputObject que causó la pérdida de enfoque.Al usar teclados en la pantalla en móvil y consola, ReturnPressedFromOnScreenKeyboard también puede desencadenar.
  • Si surge un tema más importante durante el juego, puedes ReleaseFocus de la caja de texto para que la entrada del teclado de un jugador regrese a tu juego.

Edición de texto

Un TextBox admite la selección de texto a través de sus propiedades CursorPosition y SelectionStart.Al usar GetPropertyChangedSignal, puedes detectar cuando cambia una selección.Además, es posible que los jugadores copien y peguen texto dentro de un TextBox, habilitando el Soportebásico del portapapeles.

Notificación de filtrado de texto Los juegos que facilitan la comunicación de jugador a jugador usando texto, como el chat personalizado o las etiquetas de nombre, deben filtrar adecuadamente ese texto usando TextService:FilterStringAsync() o Chat:FilterStringAsync() .Si esto no se hace correctamente, tu juego puede recibir una acción de moderación.

Muestras de código

This code sample creates a password-like interface for a TextBox, giving visual feedback on the player's input.

TextBox Secret Word

-- Place this code in a LocalScript inside a TextBox
local textBox = script.Parent
local secretWord = "roblox"
local colorNormal = Color3.new(1, 1, 1) -- white
local colorWrong = Color3.new(1, 0, 0) -- red
local colorCorrect = Color3.new(0, 1, 0) -- green
-- Initialize the state of the textBox
textBox.ClearTextOnFocus = true
textBox.Text = ""
textBox.Font = Enum.Font.Code
textBox.PlaceholderText = "What is the secret word?"
textBox.BackgroundColor3 = colorNormal
local function onFocused()
textBox.BackgroundColor3 = colorNormal
end
local function onFocusLost(enterPressed, _inputObject)
if enterPressed then
local guess = textBox.Text
if guess == secretWord then
textBox.Text = "ACCESS GRANTED"
textBox.BackgroundColor3 = colorCorrect
else
textBox.Text = "ACCESS DENIED"
textBox.BackgroundColor3 = colorWrong
end
else
-- The player stopped editing without pressing Enter
textBox.Text = ""
textBox.BackgroundColor3 = colorNormal
end
end
textBox.FocusLost:Connect(onFocusLost)
textBox.Focused:Connect(onFocused)

Resumen

Propiedades

Propiedades heredados de GuiObjectPropiedades heredados de GuiBase2d

Métodos

  • Obliga al cliente a centrarse en el TextBox.

  • Devuelve verdadero si el cuadro de texto está enfocado, o falso si no lo está.

  • ReleaseFocus(submitted : boolean):()

    Obliga al cliente a desfijar el TextBox.

Métodos heredados de GuiObject

Eventos

Eventos heredados de GuiObjectEventos heredados de GuiBase2d

Propiedades

ClearTextOnFocus

Leer paralelo

Determina si hacer clic en el TextBox limpiará su propiedad TextBox.Text

ContentText

Solo lectura
No replicado
Leer paralelo

CursorPosition

Leer paralelo

Esta propiedad determina el desplazamiento del cursor de texto en bytes, o -1 si el TextBox no está siendo editado actualmente.Un valor de 1 representa la posición antes del primer byte en la propiedad Text.Cuando se usa en conjunción con la propiedad SelectionStart, es posible tanto obtener como establecer el texto seleccionado dentro de un TextBox.

Tenga en cuenta que las unidades de esta propiedad son bytes y que muchos caracteres de idioma de Unicode como los emojis son más largos que 1 byte.Por instancia, si un jugador escribe "Hola👋" ("Hola" inmediatamente seguido por la señal de mano saludando), la posición del cursor sería 10 , no 7 , ya que el emoji usa 4 bytes.

Muestras de código

This code sample demonstrates reading the current selection of a TextBox using CursorPosition() and SelectionStart().

TextBox Selections

local textBox = script.Parent
local function showSelection()
if textBox.CursorPosition == -1 or textBox.SelectionStart == -1 then
print("No selection")
else
local selectedText = string.sub(
textBox.Text,
math.min(textBox.CursorPosition, textBox.SelectionStart),
math.max(textBox.CursorPosition, textBox.SelectionStart)
)
print('The selection is:"', selectedText, '"')
end
end
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(showSelection)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(showSelection)
Oculto
No replicado
Leer paralelo

La propiedad de fuente selecciona una de varias predefinidas fonts con las cuales el elemento de la interfaz renderizará su texto.Algunas fuentes tienen variantes audaces, italicas y/o ligeras (ya que no hay propiedades de peso de fuente o estilo de fuente).

Con la excepción de la fuente "Legacy", cada fuente renderizará texto con la altura de línea igual a la propiedad TextBox.TextSize.La fuente "Código" es la única fuente de espacio único.Tiene la propiedad única que cada personaje tiene la misma proporción de ancho y altura de 1:2.El ancho de cada personaje es aproximadamente la mitad de la propiedad TextBox.TextSize .

Esta propiedad se mantiene sincronizada con la propiedad TextBox.FontFace. Cuando se establece la fuente, el FontFace se establecerá en Font.fromEnum(value).

Muestras de código

This code sample sets a parent TextLabel's Font and Text properties to all the different fonts available.

Cycle Font

local textLabel = script.Parent
while true do
-- Iterate over all the different fonts
for _, font in pairs(Enum.Font:GetEnumItems()) do
textLabel.Font = font
textLabel.Text = font.Name
task.wait(1)
end
end

This code sample renders a list of all the available fonts.

Show All Fonts

local frame = script.Parent
-- Create a TextLabel displaying each font
for _, font in pairs(Enum.Font:GetEnumItems()) do
local textLabel = Instance.new("TextLabel")
textLabel.Name = font.Name
-- Set the text properties
textLabel.Text = font.Name
textLabel.Font = font
-- Some rendering properties
textLabel.TextSize = 24
textLabel.TextXAlignment = Enum.TextXAlignment.Left
-- Size the frame equal to the height of the text
textLabel.Size = UDim2.new(1, 0, 0, textLabel.TextSize)
-- Add to the parent frame
textLabel.Parent = frame
end
-- Layout the frames in a list (if they aren't already)
if not frame:FindFirstChildOfClass("UIListLayout") then
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.Parent = frame
end

FontFace

Leer paralelo

La propiedad FontFace es similar a la propiedad Font, pero permite establecer fuentes que no existen en el enum de fuentes.

Esta propiedad se mantiene sincronizada con la propiedad TextBox.Font.Al establecer FontFace, la fuente se establece en el valor de enumeración correspondiente o en Enum.Font.Unknown si no hay coincidencias.

LineHeight

Leer paralelo

Controla la altura de las líneas, como múltiplo del tamaño del cuadrado de la fuente, al escalar el espacio entre las líneas de texto en el TextBox.Los valores válidos van de 1.0 a 3.0, por defecto a 1.0.

MaxVisibleGraphemes

Leer paralelo

Esta propiedad controla el número máximo de grafemas (o unidades de texto) que se muestran en el TextBox, independientemente de si está mostrando el TextBox.PlaceholderText o el TextBox.Text.

Cambiar la propiedad no cambia la posición o el tamaño de los grafemas visibles - el diseño se calculará como si todos los grafemas fueran visibles.

Establecer la propiedad a -1 desactiva el límite y muestra la totalidad del TextBox.Text .

MultiLine

Leer paralelo

Cuando se establece en verdadero, el texto dentro de un TextBox es capaz de moverse a múltiples líneas. Esto también permite que los jugadores usen la tecla de entrada para moverse a una nueva línea.

OpenTypeFeatures

Leer paralelo

OpenTypeFeaturesError

Solo lectura
No replicado
Leer paralelo

PlaceholderColor3

Leer paralelo

Establece el color del texto que se usa cuando aún no se ha introducido texto en el TextBox.

PlaceholderText

Leer paralelo

Establece el texto que se muestra cuando aún no se ha introducido texto en el TextBox.

RichText

Leer paralelo

Esta propiedad determina si el TextBox renderiza la cadena TextBox.Text usando formato de texto enriquecido.El texto enriquecido usa etiquetas de marcado simples para estilizar secciones de la cadena en negrita, cursiva, colores específicos y más.

Para usar texto enriquecido, simplemente incluya etiquetas de formato en la cadena TextBox.Text.

Tenga en cuenta que cuando el TextBox tiene esta propiedad habilitada y la caja gana enfoque, el usuario podrá editar y interactuar con el cadenaXML completo, incluyendo todas las etiquetas de formato.Cuando se pierde el enfoque, el texto se analizará y renderizará automáticamente las etiquetas como texto enriquecido.

SelectionStart

Leer paralelo

Determina la posición de inicio de una selección de texto, o -1 si el TextBox no tiene rango de texto seleccionado.Si el valor es -1 o equivalente a CursorPosition, no hay rango de texto seleccionado.Esta propiedad usa la misma lógica de posicionamiento que CursorPosition.La selección de inicio será mayor que la posición del cursor si el cursor está al comienzo de una selección y menor que la posición del cursor si el cursor está al finalizar.

Muestras de código

This code sample demonstrates reading the current selection of a TextBox using CursorPosition() and SelectionStart().

TextBox Selections

local textBox = script.Parent
local function showSelection()
if textBox.CursorPosition == -1 or textBox.SelectionStart == -1 then
print("No selection")
else
local selectedText = string.sub(
textBox.Text,
math.min(textBox.CursorPosition, textBox.SelectionStart),
math.max(textBox.CursorPosition, textBox.SelectionStart)
)
print('The selection is:"', selectedText, '"')
end
end
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(showSelection)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(showSelection)

ShowNativeInput

Leer paralelo

Si se establece en verdadero, se usa la entrada nativa de la plataforma en lugar del teclado integrado de Roblox.

Text

Leer paralelo

La propiedad Text determina el contenido renderizado por el elemento de la interfaz de usuario.Las propiedades visuales de la cadena renderizada en la pantalla se determinan por TextBox.TextColor3 , TextBox.TextTransparency , TextBox.TextSize , TextBox.Font , TextBox.TextScaled , TextBox.TextWrapped , TextBox.TextXAlignment y TextBox.TextYAlignment .

Es posible renderizar emojis (por ejemplo, 😃) y otros símbolos.Estos símbolos especiales no se ven afectados por la propiedad TextBox.TextColor3.Estos se pueden pegar en Script y LocalScript objetos, así como en el campo dentro de la ventana de propiedades.

Esta propiedad puede contener caracteres de nueva línea, sin embargo, no es posible escribir caracteres de nueva línea dentro de la ventana de propiedades.Del mismo modo, esta propiedad puede contener un carácter de pestaña, pero se renderizará como un espacio en su lugar.

Muestras de código

This code sample creates a fading banner for a TextLabel. It fades text out, chooses a random string (avoiding repetition), and fades back in.

Fading Banner

local TweenService = game:GetService("TweenService")
local textLabel = script.Parent
local content = {
"Welcome to my game!",
"Be sure to have fun!",
"Please give suggestions!",
"Be nice to other players!",
"Don't grief other players!",
"Check out the shop!",
"Tip: Don't die!",
}
local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
local RNG = Random.new()
local fadeIn = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 0,
})
local fadeOut = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 1,
})
local lastIndex
while true do
-- Step 0: Fade out before doing anything
fadeOut:Play()
task.wait(tweenInfo.Time)
-- Step 1: pick content that wasn't the last displayed
local index
repeat
index = RNG:NextInteger(1, #content)
until lastIndex ~= index
-- Make sure we don't show the same thing next time
lastIndex = index
-- Step 2: show the content
textLabel.Text = content[index]
fadeIn:Play()
task.wait(tweenInfo.Time + 1)
end

This code sample repeatedly tweens a TextLabel's TextSize from 5 to 100 and fades out the text as it grows in size.

"Kaboom!" Text

local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end

This code sample renders a list of all the available fonts.

Show All Fonts

local frame = script.Parent
-- Create a TextLabel displaying each font
for _, font in pairs(Enum.Font:GetEnumItems()) do
local textLabel = Instance.new("TextLabel")
textLabel.Name = font.Name
-- Set the text properties
textLabel.Text = font.Name
textLabel.Font = font
-- Some rendering properties
textLabel.TextSize = 24
textLabel.TextXAlignment = Enum.TextXAlignment.Left
-- Size the frame equal to the height of the text
textLabel.Size = UDim2.new(1, 0, 0, textLabel.TextSize)
-- Add to the parent frame
textLabel.Parent = frame
end
-- Layout the frames in a list (if they aren't already)
if not frame:FindFirstChildOfClass("UIListLayout") then
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.Parent = frame
end

This code sample demonstrates TextWrap by spelling out a long chunk of text progressively. If the text doesn't fit, it turns a different color.

Long Text Wrapping

local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end

This code sample demonstrates emoji rendering using the Text property.

Emoji in Text

local textLabel = script.Parent
local moods = {
["happy"] = "😃",
["sad"] = "😢",
["neutral"] = "😐",
["tired"] = "😫",
}
while true do
for mood, face in pairs(moods) do
textLabel.Text = "I am feeling " .. mood .. "! " .. face
task.wait(1)
end
end

TextBounds

Solo lectura
No replicado
Leer paralelo

La propiedad de solo lectura TextBounds refleja el tamaño absoluto del texto renderizado en desplazamientos.En otras palabras, si intentas encajar texto en un rectángulo, esta propiedad reflejaría las dimensiones mínimas del rectángulo que necesitarías para encajar el texto.

Al usar TextService:GetTextSize(), puedes predecir qué serán los límites de texto en una etiqueta de texto dada una cadena, TextBox.Font , TextBox.TextSize y el tamaño del marco.

Muestras de código

This code sample dynamically resizes a TextLabel, TextButton or TextBox to match the size of its TextBounds. Try changing the minimum width/height and pasting into a LocalScript in a TextBox.

Dynamic TextBox Size

local textBox = script.Parent
-- The smallest the TextBox will go
local minWidth, minHeight = 10, 10
-- Set alignment so our text doesn't wobble a bit while we type
textBox.TextXAlignment = Enum.TextXAlignment.Left
textBox.TextYAlignment = Enum.TextYAlignment.Top
local function updateSize()
textBox.Size = UDim2.new(0, math.max(minWidth, textBox.TextBounds.X), 0, math.max(minHeight, textBox.TextBounds.Y))
end
textBox:GetPropertyChangedSignal("TextBounds"):Connect(updateSize)

TextColor3

Leer paralelo

Esta propiedad determina el color de todo el texto renderizado por un elemento GuiObject .Esta propiedad junto con TextBox.Font , TextBox.TextSize y TextBox.TextTransparency determinará las propiedades visuales del texto.El texto se renderiza después del trazado del texto ( TextBox.TextStrokeColor3 ).

¡Es importante que el texto sea fácil de leer para los jugadores! Asegúrate de elegir colores con poca o ninguna saturación, como blanco, gris o negro.Asegúrate de que el color de tu texto se contraste con el TextBox.BackgroundColor3 del elemento de la interfaz de usuario.Si el elemento tiene un fondo transparente, prueba aplicar un negro TextBox.TextStrokeColor3 para ayudar a contrastar el texto con el mundo 3D detrás de él.

Muestras de código

This code sample, when placed within a TextBox, will turn the text color red if the typed string contains no vowels (A, E, I, O or U).

Vowel Detector

local textBox = script.Parent
local function hasVowels(str)
return str:lower():find("[aeiou]")
end
local function onTextChanged()
local text = textBox.Text
-- Check for vowels
if hasVowels(text) then
textBox.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textBox.TextColor3 = Color3.new(1, 0, 0) -- Red
end
end
textBox:GetPropertyChangedSignal("Text"):Connect(onTextChanged)

This code sample creates a password-like interface for a TextBox, giving visual feedback on the player's input.

TextBox Secret Word

-- Place this code in a LocalScript inside a TextBox
local textBox = script.Parent
local secretWord = "roblox"
local colorNormal = Color3.new(1, 1, 1) -- white
local colorWrong = Color3.new(1, 0, 0) -- red
local colorCorrect = Color3.new(0, 1, 0) -- green
-- Initialize the state of the textBox
textBox.ClearTextOnFocus = true
textBox.Text = ""
textBox.Font = Enum.Font.Code
textBox.PlaceholderText = "What is the secret word?"
textBox.BackgroundColor3 = colorNormal
local function onFocused()
textBox.BackgroundColor3 = colorNormal
end
local function onFocusLost(enterPressed, _inputObject)
if enterPressed then
local guess = textBox.Text
if guess == secretWord then
textBox.Text = "ACCESS GRANTED"
textBox.BackgroundColor3 = colorCorrect
else
textBox.Text = "ACCESS DENIED"
textBox.BackgroundColor3 = colorWrong
end
else
-- The player stopped editing without pressing Enter
textBox.Text = ""
textBox.BackgroundColor3 = colorNormal
end
end
textBox.FocusLost:Connect(onFocusLost)
textBox.Focused:Connect(onFocused)

This code sample makes a TextLabel or TextButton count backwards from 10, setting the text color as it does so.

Countdown Text

-- Place this code in a LocalScript within a TextLabel/TextButton
local textLabel = script.Parent
-- Some colors we'll use with TextColor3
local colorNormal = Color3.new(0, 0, 0) -- black
local colorSoon = Color3.new(1, 0.5, 0.5) -- red
local colorDone = Color3.new(0.5, 1, 0.5) -- green
-- Loop infinitely
while true do
-- Count backwards from 10 to 1
for i = 10, 1, -1 do
-- Set the text
textLabel.Text = "Time: " .. i
-- Set the color based on how much time is left
if i > 3 then
textLabel.TextColor3 = colorNormal
else
textLabel.TextColor3 = colorSoon
end
task.wait(1)
end
textLabel.Text = "GO!"
textLabel.TextColor3 = colorDone
task.wait(2)
end

This code sample mirrors the contents of a StringValue into a TextLabel, updating and setting the color of the text as it changes.

Game State Text

local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Place a StringValue called "GameState" in the ReplicatedStorage
local vGameState = ReplicatedStorage:WaitForChild("GameState")
-- Place this code in a TextLabel
local textLabel = script.Parent
-- Some colors we'll use with TextColor3
local colorNormal = Color3.new(0, 0, 0) -- black
local colorCountdown = Color3.new(1, 0.5, 0) -- orange
local colorRound = Color3.new(0.25, 0.25, 1) -- blue
-- We'll run this function to update the TextLabel as the state of the
-- game changes.
local function update()
-- Update the text
textLabel.Text = "State: " .. vGameState.Value
-- Set the color of the text based on the current game state
if vGameState.Value == "Countdown" then
textLabel.TextColor3 = colorCountdown
elseif vGameState.Value == "Round" then
textLabel.TextColor3 = colorRound
else
textLabel.TextColor3 = colorNormal
end
end
-- Pattern: update once when we start and also when vGameState changes
-- We should always see the most updated GameState.
update()
vGameState.Changed:Connect(update)

TextDirection

Leer paralelo

TextEditable

Leer paralelo

TextEditable determina si el usuario puede cambiar el Text a través de la entrada.Se recomienda deshabilitar ClearTextOnFocus cuando esta propiedad esté deshabilitada, de lo contrario el texto podría limpiarse al enfocarse.Esta propiedad es útil para crear TextBoxes de solo lectura de los cuales se puede copiar contenido en el juego.

TextFits

Solo lectura
No replicado
Leer paralelo

Si el texto se ajusta a las restricciones de la caja de texto.

TextScaled

Leer paralelo

En lugar de usar TextScaled, te recomendamos considerar usar AutomaticSize , un nuevo método para escalar dinámicamente la interfaz que te dará el mejor resultado visual posible.

La propiedad TextScaled determina si el texto se escala para que ocupe todo el espacio del elemento de la interfaz de usuario.Cuando esto está habilitado, TextBox.TextSize se ignora y TextBox.TextWrapped se habilita automáticamente.Esta propiedad es útil para elementos de interfaz de usuario de renderizado de texto dentro de BillboardGuis .

Cuando esta propiedad se usa para la interfaz de usuario en el espacio de la pantalla, puede ser deseable usar un UITextSizeConstraint para restringir el rango de tamaños de texto posibles.

TextScaled y AutoSize Automático

Se recomienda que los desarrolladores eviten el uso de TextScaled y ajusten la interfaz de usuario para aprovechar la propiedad AutomaticSize en su lugar.Aquí están las diferencias principales entre las dos propiedades:

  • TextScaled escala el contenido (el texto) para acomodar la interfaz de usuario. Sin una consideración cuidadosa, parte del texto puede volverse ilegible si se escala demasiado pequeño.
  • AutomaticSize redimensiona la interfaz de usuario para acomodar el contenido.

Con AutomaticSize, puedes ajustar tu interfaz de usuario para que acomode el contenido (texto) mientras mantienes un tamaño de fuente consistente.Para obtener más información sobre cómo usar el tamaño automático, consulte el artículo Tamaño automático de la interfaz de usuario.

Sugerimos que no apliques ambas propiedades, TextScaled y AutomaticSize, en el mismo objeto de interfaz de usuario. Si aplicas ambas propiedades:

  • AutomaticSize determina la cantidad máxima de espacio disponible que un GuiObject puede usar (en este caso, texto)
  • TextScaled usa el espacio disponible determinado por AutomaticSize, para escalar el tamaño de la fuente para que encaje con el espacio disponible, que se expandirá hasta el tamaño máximo de la fuente (100), si no hay restricciones de tamaño
  • El resultado final será: el texto se reduce a un tamaño de fuente de 100 y el objeto de la interfaz se expandirá para adaptarse a ese texto

Usar tanto AutomaticSize como TextScaled al mismo tiempo puede resultar en diferencias de escalado significativas que cuando AutomaticSize está desactivado.

Muestras de código

This code sample demonstrates TextWrap by spelling out a long chunk of text progressively. If the text doesn't fit, it turns a different color.

Long Text Wrapping

local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end

TextSize

Leer paralelo

La propiedad TextSize determina la altura en desplazamientos de una línea de texto renderizado.La unidad está en desplazamientos, no en puntos (que se usa en la mayoría de los programas de edición de documentos).La fuente "Legacy" no tiene esta propiedad.

Muestras de código

This code sample repeatedly tweens a TextLabel's TextSize from 5 to 100 and fades out the text as it grows in size.

"Kaboom!" Text

local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end

TextStrokeColor3

Leer paralelo

La propiedad TextStrokeColor3 establece el color del trazado, o contorno, del texto renderizado.Esta propiedad y TextBox.TextStrokeTransparency determinan las propiedades visuales del trazado del texto.

El trazado de texto se renderiza antes del texto normal y es simplemente 4 representaciones del mismo texto en +/- 1 desplazamientos en cada dirección.El renderizado del trazado de texto funciona de forma independiente y idéntica a TextBox.TextColor3 y TextBox.TextTransparency .

Muestras de código

This code sample oscillates a TextLabel's TextStrokeTransparency so that it blinks the highlight of a text.

Text Highlight Oscillation

local textLabel = script.Parent
-- How fast the highlight ought to blink
local freq = 2
-- Set to yellow highlight color
textLabel.TextStrokeColor3 = Color3.new(1, 1, 0)
while true do
-- math.sin oscillates from -1 to 1, so we change the range to 0 to 1:
local transparency = math.sin(workspace.DistributedGameTime * math.pi * freq) * 0.5 + 0.5
textLabel.TextStrokeTransparency = transparency
task.wait()
end

TextStrokeTransparency

Leer paralelo

La propiedad TextStrokeTransparency establece la transparencia del trazado, o contorno, del texto renderizado.Esta propiedad y TextBox.TextStrokeColor3 determinan las propiedades visuales del trazado del texto.

El trazado de texto se renderiza antes del texto normal y es simplemente 4 representaciones del mismo texto en +/- 1 desplazamientos en cada dirección.El renderizado del trazado de texto funciona de forma independiente y idéntica a TextBox.TextColor3 y TextBox.TextTransparency .Dado que el trazado de texto es simplemente múltiples representaciones de la misma transparencia, esta propiedad es esencialmente multiplicativa sobre sí misma cuatro veces (por ejemplo,una transparencia de trazo de texto de 0.5 aparece aproximadamente igual a la transparencia del texto de 0.0625, o 0.5^4).Por lo tanto, se recomienda establecer la transparencia del trazado de texto en un valor que oscile entre 0.75 y 1 para un efecto más sutil.

Muestras de código

This code sample oscillates a TextLabel's TextStrokeTransparency so that it blinks the highlight of a text.

Text Highlight Oscillation

local textLabel = script.Parent
-- How fast the highlight ought to blink
local freq = 2
-- Set to yellow highlight color
textLabel.TextStrokeColor3 = Color3.new(1, 1, 0)
while true do
-- math.sin oscillates from -1 to 1, so we change the range to 0 to 1:
local transparency = math.sin(workspace.DistributedGameTime * math.pi * freq) * 0.5 + 0.5
textLabel.TextStrokeTransparency = transparency
task.wait()
end

TextTransparency

Leer paralelo

La propiedad TextColor3 determina la transparencia de todo el texto renderizado por un elemento de interfaz de usuario.Esta propiedad junto con TextBox.Font , TextBox.TextSize y TextBox.TextColor3 determinará las propiedades visuales del texto.El texto se renderiza después del trazado del texto ( TextBox.TextStrokeTransparency ).

Desaparecer texto al usar un bucle for numérico es una fantástica manera de llamar la atención del jugador sobre el texto que aparece en la pantalla.


-- Count backwards from 1 to 0, decrementing by 0.1
for i = 1, 0, -0.1 do
textLabel.TextTransparency = i
task.wait(0.1)
end

Muestras de código

This code sample creates a fading banner for a TextLabel. It fades text out, chooses a random string (avoiding repetition), and fades back in.

Fading Banner

local TweenService = game:GetService("TweenService")
local textLabel = script.Parent
local content = {
"Welcome to my game!",
"Be sure to have fun!",
"Please give suggestions!",
"Be nice to other players!",
"Don't grief other players!",
"Check out the shop!",
"Tip: Don't die!",
}
local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
local RNG = Random.new()
local fadeIn = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 0,
})
local fadeOut = TweenService:Create(textLabel, tweenInfo, {
TextTransparency = 1,
})
local lastIndex
while true do
-- Step 0: Fade out before doing anything
fadeOut:Play()
task.wait(tweenInfo.Time)
-- Step 1: pick content that wasn't the last displayed
local index
repeat
index = RNG:NextInteger(1, #content)
until lastIndex ~= index
-- Make sure we don't show the same thing next time
lastIndex = index
-- Step 2: show the content
textLabel.Text = content[index]
fadeIn:Play()
task.wait(tweenInfo.Time + 1)
end

This code sample repeatedly tweens a TextLabel's TextSize from 5 to 100 and fades out the text as it grows in size.

"Kaboom!" Text

local textLabel = script.Parent
textLabel.Text = "Kaboom!"
while true do
for size = 5, 100, 5 do
textLabel.TextSize = size
textLabel.TextTransparency = size / 100
task.wait()
end
task.wait(1)
end

TextTruncate

Leer paralelo

Controla la truncación del texto que se muestra en este TextBox.

TextWrapped

Leer paralelo

Cuando se habilita, esta propiedad renderizará texto en múltiples líneas dentro del espacio de un elemento TextBox para que TextBox.TextBounds nunca supere el GuiBase2d.AbsoluteSize del elemento de la interfaz gráfica de usuario.

Se logra al dividir largas líneas de texto en múltiples líneas.Las interrupciones de línea preferirán espacio en blanco; si una palabra larga sin interrupciones excede el ancho del elemento, esa palabra se dividirá en múltiples líneas.

Si se producirían más roturas de líneas que causaran que la altura vertical del texto (el componente Y de TextBox.TextBounds) excediera la altura vertical del elemento (el componente Y de GuiBase2d.AbsoluteSize), entonces esa línea no se renderizará en todos/todas.

Muestras de código

This code sample demonstrates TextWrap by spelling out a long chunk of text progressively. If the text doesn't fit, it turns a different color.

Long Text Wrapping

local textLabel = script.Parent
-- This text wrapping demo is best shown on a 200x50 px rectangle
textLabel.Size = UDim2.new(0, 200, 0, 50)
-- Some content to spell out
local content = "Here's a long string of words that will "
.. "eventually exceed the UI element's width "
.. "and form line breaks. Useful for paragraphs "
.. "that are really long."
-- A function that will spell text out two characters at a time
local function spellTheText()
-- Iterate from 1 to the length of our content
for i = 1, content:len() do
-- Get a substring of our content: 1 to i
textLabel.Text = content:sub(1, i)
-- Color the text if it doesn't fit in our box
if textLabel.TextFits then
textLabel.TextColor3 = Color3.new(0, 0, 0) -- Black
else
textLabel.TextColor3 = Color3.new(1, 0, 0) -- Red
end
-- Wait a brief moment on even lengths
if i % 2 == 0 then
task.wait()
end
end
end
while true do
-- Spell the text with scale/wrap off
textLabel.TextWrapped = false
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with wrap on
textLabel.TextWrapped = true
textLabel.TextScaled = false
spellTheText()
task.wait(1)
-- Spell the text with text scaling on
-- Note: Text turns red (TextFits = false) once text has to be
-- scaled down in order to fit within the UI element.
textLabel.TextScaled = true
-- Note: TextWrapped is enabled implicitly when TextScaled = true
--textLabel.TextWrapped = true
spellTheText()
task.wait(1)
end

TextXAlignment

Leer paralelo

TextXAlignment determina el alineamiento horizontal (eje X) del texto renderizado dentro del espacio de un elemento de interfaz de usuario.Funciona de manera similar a la propiedad de alineación de texto de CSS, con valores de izquierda, derecha y centro (no hay opción de justificación).Para la izquierda y la derecha, el texto se renderiza de tal manera que los límites de texto izquierdo/derecho solo tocan el borde del rectángulo de elementos de la interfaz de usuario.Para el centro, cada línea de texto se centra en el centro muy del elemento rectangular de la interfaz de usuario.

Esta propiedad se usa junto con TextBox.TextYAlignment para determinar completamente el alineamiento del texto en ambos ejes.Esta propiedad no afectará a las propiedades de solo lectura TextBox.TextBounds y TextBox.TextFits.

Muestras de código

This code sample shows all the different text alignment combinations by iterating over each enum item. It is meant to be placed within a TextLabel, TextButton or TextBox.

Text Alignment

-- Paste this in a LocalScript within a TextLabel/TextButton/TextBox
local textLabel = script.Parent
local function setAlignment(xAlign, yAlign)
textLabel.TextXAlignment = xAlign
textLabel.TextYAlignment = yAlign
textLabel.Text = xAlign.Name .. " + " .. yAlign.Name
end
while true do
-- Iterate over both TextXAlignment and TextYAlignment enum items
for _, yAlign in pairs(Enum.TextYAlignment:GetEnumItems()) do
for _, xAlign in pairs(Enum.TextXAlignment:GetEnumItems()) do
setAlignment(xAlign, yAlign)
task.wait(1)
end
end
end

TextYAlignment

Leer paralelo

TextYAlignment determina el alineamiento vertical (eje Y) del texto renderizado dentro del espacio de un elemento de interfaz de usuario.Para la parte superior e inferior, el texto se renderiza de tal manera que los límites de texto superior/inferior solo tocan el borde del rectángulo de elementos de la interfaz de usuario.Para el centro, el texto se renderiza de tal manera que hay un espacio igual desde los límites superiores del texto hasta la parte superior del elemento y los límites inferiores del texto hasta la parte inferior del elemento.

Esta propiedad se usa junto con TextBox.TextXAlignment para determinar completamente el alineamiento del texto en ambos ejes.Esta propiedad no afectará a las propiedades de solo lectura TextBox.TextBounds y TextBox.TextFits.

Muestras de código

This code sample shows all the different text alignment combinations by iterating over each enum item. It is meant to be placed within a TextLabel, TextButton or TextBox.

Text Alignment

-- Paste this in a LocalScript within a TextLabel/TextButton/TextBox
local textLabel = script.Parent
local function setAlignment(xAlign, yAlign)
textLabel.TextXAlignment = xAlign
textLabel.TextYAlignment = yAlign
textLabel.Text = xAlign.Name .. " + " .. yAlign.Name
end
while true do
-- Iterate over both TextXAlignment and TextYAlignment enum items
for _, yAlign in pairs(Enum.TextYAlignment:GetEnumItems()) do
for _, xAlign in pairs(Enum.TextXAlignment:GetEnumItems()) do
setAlignment(xAlign, yAlign)
task.wait(1)
end
end
end

Métodos

CaptureFocus

()

Obliga al cliente a centrarse en el TextBox.


Devuelve

()

Muestras de código

This code sample causes the client to focus on the parent TextBox when the Q key is pressed by the player.

TextBox:CaptureFocus

local ContextActionService = game:GetService("ContextActionService")
local ACTION_NAME = "FocusTheTextBox"
local textBox = script.Parent
local function handleAction(actionName, inputState, _inputObject)
if actionName == ACTION_NAME and inputState == Enum.UserInputState.End then
textBox:CaptureFocus()
end
end
ContextActionService:BindAction(ACTION_NAME, handleAction, false, Enum.KeyCode.Q)

IsFocused

Devuelve verdadero si el cuadro de texto está enfocado, o falso si no lo está.


Devuelve

ReleaseFocus

()

Obliga al cliente a desfijar el TextBox. El parámetro submitted le permite anular el parámetro enterPressed en el evento TextBox.FocusLost.

Este elemento debe usarse con un LocalScript para funcionar como se espera en el modo en línea.

El código mostrado a continuación obligará al cliente a desfocar el 'TextBox' 5 segundos después de que se seleccione:


local TextBox = script.Parent
TextBox.Focused:Connect(function()
wait(5)
TextBox:ReleaseFocus()
end)

Tenga en cuenta que el ejemplo anterior asume que está en un LocalScript, como hijo de un TextBox.

Parámetros

submitted: boolean
Valor predeterminado: false

Devuelve

()

Muestras de código

The code shown below will force the client to unfocus the 'TextBox' 5 seconds after it's selected:

TextBox:ReleaseFocus

local textBox = script.Parent
local function onFocused()
task.wait(5)
textBox:ReleaseFocus()
end
textBox.Focused:Connect(onFocused)

Eventos

FocusLost

Se activa cuando el cliente deja que su enfoque salga de la caja de texto - por lo general, cuando un cliente hace clic/toca fuera de la caja de texto.Esto también se activa si un TextBox fuerza el enfoque en el usuario.

Se puede usar junto con TextBox.Focused para rastrear cuándo una caja de texto gana y pierde enfoque.

Vea también el UserInputService.TextBoxFocused y UserInputService.TextBoxFocusReleased para funciones similares que dependen del servicio UserInputService.

Este evento solo se disparará cuando se use en un LocalScript .

Parámetros

enterPressed: boolean

Un booleano que indica si el cliente presionó Enter para perder el enfoque ( verdadero ) o no ( falso ).

inputThatCausedFocusLoss: InputObject

Una instancia InputObject que indica el tipo de entrada que causó que la caja de texto perdiera el enfoque.


Muestras de código

The example shown below will print "Focus was lost because enter was pressed!" whenever the TextBox loses focus as a result of the enter key being pressed.

TextBox.FocusLost1

local gui = script.Parent
local textBox = gui.TextBox
local function focusLost(enterPressed)
if enterPressed then
print("Focus was lost because enter was pressed!")
else
print("Focus was lost without enter being pressed")
end
end
textBox.FocusLost:Connect(focusLost)

This example works when placed in a LocalScript that is the child of a TextBox. When the TextBox loses focus, the example prints either:

  1. "Player pressed Enter" - if the TextBox lost focus because the player pressed the Enter key. or
  2. "Player pressed InputObject.KeyCode" - where "KeyCode" is the InputObject KeyCode property of the input that caused the TextBox to lose focus. For example, pressing the Escape (esc) key to exit TextBox focus returns an InputObject instance with the KeyCode 'InputObject.Escape'.
FocusLost

local textBox = script.Parent
local function onFocusLost(enterPressed, inputThatCausedFocusLost)
if enterPressed then
print("Player pressed Enter")
else
print("Player pressed", inputThatCausedFocusLost.KeyCode)
end
end
textBox.FocusLost:Connect(onFocusLost)

Focused

Se enciende cuando el TextBox gana enfoque - por ejemplo, cuando un cliente hace clic/toca en un TextBox para comenzar la entrada de texto.Esto también se activa si un TextBox fuerza el enfoque en el usuario.

Se puede usar junto con TextBox.FocusLost para rastrear cuándo una caja de texto gana y pierde enfoque.

Vea también el UserInputService.TextBoxFocused y UserInputService.TextBoxFocusReleased para funciones similares que dependen del servicio UserInputService.

Este evento solo se disparará cuando se use en un LocalScript .


Muestras de código

This example works when placed in a LocalScript that is the child of a TextBox. When the TextBox gains focus, the example prints "Focus".

Focus

local textBox = script.Parent
local function onFocused()
print("Focused")
end
textBox.Focused:Connect(onFocused)

ReturnPressedFromOnScreenKeyboard