TextBox

Mostrar obsoleto

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.

Uma Caixa de Texto permite que o jogador forneça uma entrada de texto.Comporta-se de forma semelhante a um TextButton, exceto que uma única Caixa de Texto pode ser colocada em destaque clicando, tocando ou selecionando o gamepad.Enquanto estiver focado, o jogador pode usar um teclado para alterar a propriedade Text.

  • Se não houver texto, o PlaceholderText será visível. Isso é útil solicitando aos jogadores do tipo ou formato de dados que eles devem inserir.
  • Por padrão, a propriedade ClearTextOnFocus está habilitada e garante que não haja texto existente quando um TextBox for focado.Isso pode não ser desejável para texto que deve ser editável pelo jogador.
  • A propriedade MultiLine permite que os jogadores insiram várias linhas de texto com caracteres de nova linha ( \n ).

O ContextActionService honra os atalhos de tecla da Caixa de Texto e impedirá automaticamente que os eventos de pressão de tecla sejam transmitidos para ações vinculadas com ContextActionService:BindAction().UserInputService.InputBegan e eventos relacionados ainda serão disparados enquanto uma Caixa de Texto estiver em foco.

Estado Focado

É possível detectar e alterar o estado de foco de um TextBox:

  • Você pode usar CaptureFocus quando um diálogo aparece para que o jogador não precise clicar em uma Caixa de Texto quando ela ficar disponível; você pode usar ContextActionService:BindAction() para vincular uma determinada tecla para focar uma Caixa de Texto usando essa função.Quando um TextBox entra em foco, o evento Focused é acionado.
  • Você pode detectar se uma caixa de texto específica está em destaque usando IsFocused . Alternativamente, UserInputService:GetFocusedTextBox() pode ser usado para verificar se alguma caixa de texto está em destaque.
  • Quando o jogador terminar de inserir texto, o evento é acionado, indicando se o usuário pressionou para enviar o texto junto com o que causou a perda de foco.Ao usar teclados na tela em dispositivos móveis e de console, ReturnPressedFromOnScreenKeyboard também pode Iniciar / executar.
  • Se algum assunto mais importante surgir durante o jogabilidade, você pode ReleaseFocus da Caixa de Texto para que a entrada do teclado de um jogador retorne ao seu jogo.

Edição de Texto

Uma caixa de texto suporta seleção de texto através de suas propriedades CursorPosition e SelectionStart.Usando GetPropertyChangedSignal, você pode detectar quando uma seleção muda.Além disso, é possível que os jogadores copiem e colem texto dentro de uma Caixa de Texto, ativando o Suportebásico ao clipe.

Aviso de Filtragem de Texto Jogos que facilitam a comunicação de jogador para jogador usando texto, como chat personalizado ou etiquetas de nome, devem filtrar corretamente esse texto usando TextService:FilterStringAsync() ou Chat:FilterStringAsync() .Se isso não for feito corretamente, o seu jogo pode receber ação de moderação.

Amostras 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)

Resumo

Propriedades

Propriedades herdados de GuiObjectPropriedades herdados de GuiBase2d

Métodos

Métodos herdados de GuiObject

Eventos

Eventos herdados de GuiObjectEventos herdados de GuiBase2d

Propriedades

ClearTextOnFocus

Ler Parallel

Determina se clicar na caixa de texto limpará sua propriedade TextBox.Text

ContentText

Somente leitura
Não replicado
Ler Parallel

CursorPosition

Ler Parallel

Essa propriedade determina o deslocamento do cursor de texto em bytes ou -1 se o TextBox não estiver sendo editado.Um valor de 1 representa a posição antes do primeiro byte na propriedade Text.Quando usado em conjunto com a propriedade SelectionStart, é possível obter e definir o texto selecionado dentro de um TextBox.

Observe que as unidades desta propriedade são bytes e que muitos caracteres de idioma como emojis são mais longos do que 1 byte.Por instância, se um jogador digitar "Hello👋" ("Hello" imediatamente seguido pelo sinal de mão balançante), a posição do cursor seria 10 , não 7 , já que o emoji usa 4 bytes.

Amostras 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
Não replicado
Ler Parallel

A propriedade da Fonte seleciona uma das várias predefinidas fonts com as quais o elemento da interface renderizará seu texto.Algumas fontes têm variantes ousadas, italicas e/ou leves (pois não há propriedades de peso de fonte ou estilo de fonte).

Com a exceção da fonte "Legacy", cada fonte renderizará texto com a altura da linha igual à propriedade TextBox.TextSize.A fonte "Código" é a única fonte monoespacial.Ela tem a propriedade única que cada personagem tem a mesma largura e proporção de altura de 1:2 exata.A largura de cada personagem é aproximadamente metade da propriedade TextBox.TextSize .

Essa propriedade é mantida em sincronia com a propriedade TextBox.FontFace. Ao definir a Fonte, o FontFace será definido como Font.fromEnum(value).

Amostras 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

Ler Parallel

A propriedade FontFace é semelhante à propriedade Font, mas permite definir fontes que não existem no enum de fontes.

Essa propriedade é mantida em sincronia com a propriedade TextBox.Font.Ao definir o FontFace, a fonte é definida para o valor de enum correspondente ou para Enum.Font.Unknown se não houver correspondências.

LineHeight

Ler Parallel

Controla a altura das linhas, como um múltiplo do tamanho em quadrado da fonte, ao escalonar o espaçamento entre linhas de texto no TextBox.Os valores válidos variam de 1.0 a 3.0, padrão para 1.0.

MaxVisibleGraphemes

Ler Parallel

Essa propriedade controla o número máximo de grafemas (ou unidades de texto) que são mostrados no TextBox, independentemente de estar mostrando o TextBox.PlaceholderText ou o TextBox.Text.

Mudar a propriedade não muda a posição ou o tamanho dos gráficos visíveis - o layout será calculado como se todos os gráficos fossem visíveis.

Definir a propriedade para -1 desabilita o limite e mostra a totalidade do TextBox.Text .

MultiLine

Ler Parallel

Quando definido como verdadeiro, o texto dentro de uma TextBox é capaz de se mover para várias linhas. Isso também permite que os jogadores usem a tecla de entrada para se mover para uma nova linha.

OpenTypeFeatures

Ler Parallel

OpenTypeFeaturesError

Somente leitura
Não replicado
Ler Parallel

PlaceholderColor3

Ler Parallel

Define a cor do texto que é usada quando nenhum texto foi inserido na TextBox ainda.

PlaceholderText

Ler Parallel

Define o texto que será exibido quando nenhum texto foi inserido na TextBox ainda.

RichText

Ler Parallel

Essa propriedade determina se o TextBox renderiza a string TextBox.Text usando formatação de texto rico.O texto rico usa tags de marcação simples para estilizar seções da string em negrito, itálico, cores específicas e muito mais.

Para usar texto rico, basta incluir tags de formatação na string / cadeia / textoTextBox.Text.

Observe que quando o TextBox tem essa propriedade habilitada e a caixa ganha foco, o usuário poderá editar e interagir com o XML completo, incluindo todas as tags de formatação.Quando o foco é perdido, o texto será automaticamente analisado e renderizado como texto rico.

SelectionStart

Ler Parallel

Determina a posição inicial de uma seleção de texto ou -1 se a Caixa de Texto não tiver alcance de texto selecionado.Se o valor for -1 ou equivalente a CursorPosition, não há nenhum alcance de texto selecionado.Essa propriedade usa a mesma lógica de posicionamento como CursorPosition.A seleção inicial será maior que a posição do cursor se o cursor estiver no início de uma seleção e menor que a posição do cursor se o cursor estiver no terminar/parar/sair.

Amostras 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

Ler Parallel

Se definido como verdadeiro, o input nativo para a plataforma é usado em vez do teclado integrado do Roblox.

Text

Ler Parallel

A propriedade Texto determina o conteúdo renderizado pelo elemento de UI.As propriedades visuais da string renderizada na tela são determinadas por TextBox.TextColor3 , TextBox.TextTransparency , TextBox.TextSize , TextBox.Font , TextBox.TextScaled , TextBox.TextWrapped , TextBox.TextXAlignment e TextBox.TextYAlignment.

É possível renderizar emojis (por exemplo, 😃) e outros símbolos.Esses símbolos especiais não são afetados pela propriedade TextBox.TextColor3.Estes podem ser colados em Script e LocalScript objetos, assim como o campo dentro da janela Propriedades.

Essa propriedade pode conter caracteres de nova linha, no entanto, não é possível digitar caracteres de nova linha na janela Propriedades.Da mesma forma, esta propriedade pode conter um personagem de aba, mas renderizará como um espaço em vez disso.

Amostras 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

Somente leitura
Não replicado
Ler Parallel

A propriedade de leitura exclusiva TextBounds reflete o tamanho absoluto do texto renderizado em deslocamentos.Em outras palavras, se você tentasse encaixar texto em um retângulo, essa propriedade refletiria as dimensões mínimas do retângulo que você precisaria para encaixar o texto.

Usando TextService:GetTextSize() , você pode prever o que TextBounds será em um TextLabel dado uma string / cadeia / texto, TextBox.Font , TextBox.TextSize e tamanho do quadro.

Amostras 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

Ler Parallel

Essa propriedade determina a cor de todo o texto renderizado por um elemento GuiObject .Essa propriedade, junto com TextBox.Font , TextBox.TextSize e TextBox.TextTransparency determinará as propriedades visuais do texto.O texto é renderizado após o traço de texto ( TextBox.TextStrokeColor3 ).

É importante que o texto seja facilmente lido por jogadores! Certifique-se de escolher cores com pouca ou nenhuma saturação, como branco, cinza ou preto.Certifique-se de que a cor do seu texto é contrastada pelo TextBox.BackgroundColor3 do elemento da interface do usuário.Se o elemento tiver um plano de fundo transparente, tente aplicar um preto TextBox.TextStrokeColor3 para ajudar a contrastar o texto com o mundo 3D por trás dele.

Amostras 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

Ler Parallel

TextEditable

Ler Parallel

TextEditable determina se o usuário pode alterar o Text através da entrada.Recomenda-se desativar ClearTextOnFocus quando essa propriedade estiver desativada, caso contrário, o Texto pode ser limpo no foco.Essa propriedade é útil para fazer TextBoxes leitura-somente a partir dos quais o conteúdo pode ser copiado no jogo.

TextFits

Somente leitura
Não replicado
Ler Parallel

Se o texto está dentro das restrições da Caixa de Texto.

TextScaled

Ler Parallel

Em vez de usar TextScaled, recomendamos que você considere usar AutomaticSize, um novo método para dimensionar dinamicamente a interface que lhe dará o melhor resultado visual possível.

A propriedade TextScaled determina se o texto é escalado para preencher todo o espaço do elemento de UI.Quando isso é ativado, TextBox.TextSize é ignorado e TextBox.TextWrapped é ativado automaticamente.Essa propriedade é útil para elementos de interface de renderização de texto dentro de BillboardGuis .

Quando esta propriedade é usada para UI de espaço de tela, pode ser desejável usar um UITextSizeConstraint para restringir o alcance de tamanhos de texto possíveis.

TextScaled e Tamanho Automático

Recomenda-se que os desenvolvedores evitem o uso de TextScaled e ajustem a interface de usuário para aproveitar a propriedade AutomaticSize, em vez disso.Aqui estão as diferenças principais entre as duas propriedades:

  • O TextScaled escalona o conteúdo (texto) para acomodar a interface de usuário. Sem uma consideração cuidadosa, algum texto pode se tornar ilegível se for escalado muito pequeno.
  • O tamanho automático redimensiona a interface para acomodar o conteúdo.

Com o Tamanho Automático, você pode ajustar sua interface para acomodar o conteúdo (texto) enquanto mantém um tamanho de fonte consistente.Para mais informações sobre como usar dimensionamento automático, veja o artigo Tamanho automático da interface de usuário.

Sugerimos que você não aplique TextScaled e AutomaticSize no mesmo Objetode UI. Se você aplicar ambas as propriedades:

  • O tamanho automático determina a quantidade máxima de espaço disponível que um GuiObject pode usar (neste caso, texto)
  • O TextScaled usa o espaço disponível determinado pelo Tamanho Automático, para escalar o tamanho da fonte para se encaixar no espaço disponível, que se expandirá até o tamanho máximo da fonte (100), se não houver restrições de tamanho
  • O resultado final será: o texto vai para 100 tamanhos de fonte e o objeto da interface expandirá para caber nesse texto

Usar tanto o Tamanho Automático quanto o TextScaled ao mesmo tempo pode resultar em diferenças significativas de escalonamento do que quando o Tamanho Automático está desligado.

Amostras 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

Ler Parallel

A propriedade TextSize determina a altura em ofertas de uma linha de texto renderizado.A unidade está em deslocamentos, não em pontos (que são usados na maioria dos programas de edição de documentos).A fonte "Legacy" não possui essa propriedade.

Amostras 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

Ler Parallel

A propriedade TextStrokeColor3 define a cor do traço, ou contorno, do texto renderizado.Essa propriedade e TextBox.TextStrokeTransparency determinam as propriedades visuais do traço de texto.

O traço de texto é renderizado antes do texto normal e é simplesmente 4 renderizações do mesmo texto em +/- 1 deslocamentos de pixel em cada direção.O renderizamento de traços de texto funciona de forma independente e idêntica a TextBox.TextColor3 e TextBox.TextTransparency.

Amostras 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

Ler Parallel

A propriedade TextStrokeTransparency define a transparência do traço, ou contorno, do texto renderizado.Essa propriedade e TextBox.TextStrokeColor3 determinam as propriedades visuais do traço de texto.

O traço de texto é renderizado antes do texto normal e é simplesmente 4 renderizações do mesmo texto em +/- 1 deslocamentos de pixel em cada direção.O renderizamento de traços de texto funciona de forma independente e idêntica a TextBox.TextColor3 e TextBox.TextTransparency.Como o traço de texto é simplesmente várias renderizações da mesma transparência, essa propriedade é essencialmente multiplicativa em si mesma quatro vezes (por exemplo,uma Transparência do Traço de Texto de 0,5 aparece aproximadamente igual à Transparência do Texto de 0,0625 ou 0,5^4).Portanto, é recomendado definir a transparência do traço de texto para um valor na faixa de 0,75 a 1 para um efeito mais sutil.

Amostras 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

Ler Parallel

A propriedade TextColor3 determina a transparência de todo o texto renderizado por um elemento de UI.Essa propriedade, junto com TextBox.Font , TextBox.TextSize e TextBox.TextColor3 determinará as propriedades visuais do texto.O texto é renderizado após o traço de texto ( TextBox.TextStrokeTransparency ).

Desaparecer texto ao usar um ciclo for numérico é uma maneira fantástica de chamar a atenção de um jogador para o texto que aparece na tela.


-- 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

Amostras 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

Ler Parallel

Controla a truncagem do texto exibido nesta Caixa de Texto.

TextWrapped

Ler Parallel

Quando ativado, esta propriedade renderizará texto em várias linhas dentro do espaço de um elemento TextBox para que TextBox.TextBounds nunca exceda o GuiBase2d.AbsoluteSize do elemento GUI.

Isso é alcançado ao quebrar longas linhas de texto em várias linhas.Quebras de linha preferirão espaço em branco; se uma palavra longa não quebrada exceder a largura do elemento, essa palavra será dividida em várias linhas.

Se mais quebras de linha causassem o excesso da altura vertical do texto (o componente Y de TextBox.TextBounds) de exceder a altura vertical do elemento (o componente Y de GuiBase2d.AbsoluteSize), então essa linha não será renderizada de forma todas / todos.

Amostras 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

Ler Parallel

O TextXAlignment determina o alinhamento horizontal (eixo X) do texto renderizado dentro do espaço de um elemento de UI.Ela funciona de forma semelhante à propriedade de alinhamento de texto do CSS, com valores de esquerda, direita e centro (não há opção de justificar).Para Esquerda e Direita, o texto é renderizado de tal forma que os limites de texto esquerdo/direito apenas toquem a borda do retângulo do elemento da interface.Para o Centro, cada linha de texto é centrada no centro da retângulo do elemento da UI.

Essa propriedade é usada em conjunto com TextBox.TextYAlignment para determinar completamente o alinhamento do texto em ambos os eixos.Essa propriedade não afetará as propriedades de leitura somente TextBox.TextBounds e TextBox.TextFits.

Amostras 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

Ler Parallel

O alinhamento de texto determina o alinhamento vertical (eixo Y) do texto renderizado dentro do espaço de um elemento de UI.Para Cima e Para Baixo, o texto é renderizado de tal forma que os limites de texto superior/inferior apenas toquem a borda do retângulo de elemento de UI.Para o Centro, o texto é renderizado de forma que haja um espaço igual a partir dos limites superiores do texto até o topo do elemento e os limites inferiores do texto até o fundo do elemento.

Essa propriedade é usada em conjunto com TextBox.TextXAlignment para determinar completamente o alinhamento do texto em ambos os eixos.Essa propriedade não afetará as propriedades de leitura somente TextBox.TextBounds e TextBox.TextFits.

Amostras 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

()

Força o cliente a se concentrar na TextBox.


Devolução

()

Amostras 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

Retorna verdadeiro se a caixa de texto estiver focada, ou falso se não estiver.


Devolução

ReleaseFocus

()

Força o cliente a desfocar a TextBox. O parâmetro submitted permite que você substitua o parâmetro enterPressed no evento TextBox.FocusLost.

Este item deve ser usado com um LocalScript para funcionar como esperado no modo online.

O código mostrado abaixo forçará o cliente a desfocar o 'TextBox' 5 segundos após ser selecionado:


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

Por favor, tenha em mente que o exemplo acima supõe que está em um LocalScript, como filho de uma TextBox.

Parâmetros

submitted: boolean
Valor Padrão: false

Devolução

()

Amostras 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

Incêndios quando o cliente deixa seu foco sair da Caixa de Texto - geralmente quando um cliente clica/toca fora da Caixa de Texto.Isso também dispara se uma TextBox forçar o foco no usuário.

Pode ser usado ao lado de TextBox.Focused para rastrear quando uma TextBox ganha e perde foco.

Veja também o UserInputService.TextBoxFocused e UserInputService.TextBoxFocusReleased para funções semelhantes que dependem do serviço UserInputService.

Este evento só será disparado quando usado em um LocalScript .

Parâmetros

enterPressed: boolean

Um booleano que indica se o cliente pressionou Enter para perder o foco ( verdadeiro ) ou não ( falso ).

inputThatCausedFocusLoss: InputObject

Uma instância InputObject que indica o tipo de entrada que causou a perda de foco da TextBox.


Amostras 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

Incêndios quando o TextBox ganha foco - geralmente quando um cliente clica/toca em um TextBox para começar a inserir texto.Isso também dispara se uma TextBox forçar o foco no usuário.

Pode ser usado ao lado de TextBox.FocusLost para rastrear quando uma TextBox ganha e perde foco.

Veja também o UserInputService.TextBoxFocused e UserInputService.TextBoxFocusReleased para funções semelhantes que dependem do serviço UserInputService.

Este evento só será disparado quando usado em um LocalScript .


Amostras 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