TextBox

显示已弃用

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

一个 文本框 允许玩家提供文本输入。它与 TextButton 类似,除了单个文本框可以通过单击、点击或游戏手柄选择获得焦点。当处于焦点时,玩家可以使用键盘更改 Text 属性。

  • 如果没有文本,PlaceholderText将可见。这有助于提示玩家输入的数据类型或格式。
  • 默认情况下,ClearTextOnFocus 属性已启用,确保在 TextBox 焦点时没有现有文本。这可能不适合玩家可以编辑的文本。
  • MultiLine 属性允许玩家输入多行文本,包括新行角色(\n)。

The ContextActionService 荣誉 TextBox 键绑和将自动防止键按事件被传递到与 ContextActionService:BindAction() 绑定的行动。UserInputService.InputBegan 和相关事件仍会在 TextBox 处于焦点时发射。

焦点状态

可以检测并更改 TextBox 的焦点状态:

文本编辑

文本框通过其 CursorPositionSelectionStart 属性支持文本选择。使用 GetPropertyChangedSignal , 您可以检测到选择更改时。此外,玩家还可以在 TextBox 内复制并粘贴文本,启用基本剪贴板协助。

文本筛选通知 使用文本进行玩家对玩家通信的游戏,例如自定义聊天或名称标签,必须使用 TextService:FilterStringAsync()Chat:FilterStringAsync() 进行正确的筛选。如果没有正确执行,你的游戏可能会收到管理动作。

代码示例

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)

概要

属性

继承自GuiObject属性继承自GuiBase2d属性

方法

继承自GuiObject方法

活动

继承自GuiObject活动继承自GuiBase2d活动

属性

ClearTextOnFocus

读取并联

决定单击文本框会否清除其 TextBox.Text 属性

ContentText

只读
未复制
读取并联

CursorPosition

读取并联

这个属性决定了文本滚动器在字节中的偏移,或 -1 如果 TextBox 目前未被编辑。值 1 表示 Text 属性中第一个字节之前的位置。当与 SelectionStart 属性一起使用时,可以在 TextBox 中同时获取和设置选定的文本。

请注意,该属性的单位是 字节 ,许多Unicode字符,例如表情符号,长度超过1字节。例实例,如果玩家键入“Hello👋”(“Hello”立即跟随挥手标志),鼠标位置将为 10 ,而不是 7 ,因为表情符号使用了 4 字节。

代码示例

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)
隐藏
未复制
读取并联

字体属性选择几个预定义的 fonts 中的一个,用于 UI 元素渲染其文本。一些字体具有粗体、斜体和/或浅色变体(因为没有字体重量或字体风格属性)。

除了“遗产”字体外,每个字体都会以行高度等于 TextBox.TextSize 属性渲染文本。“代码”字体是唯一的单空间字体。它具有独特的属性,每个角色的宽度和高度比率都是 1:2 的完全相同。每个字符的宽度大约是 TextBox.TextSize 属性的一半。

该属性与 TextBox.FontFace 属性保持同步。当设置字体时,字体面将设置为 Font.fromEnum(value)

代码示例

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

读取并联

FontFace 属性与 Font 属性相似,但允许设置不存在于 Font 枚列中的字体。

该属性与 TextBox.Font 属性保持同步。当设置字体时,字体将设置为相应的枚举值或 Enum.Font.Unknown 如果没有匹配。

LineHeight

读取并联

通过在 TextBox 中缩放文本行之间的间距来控制线的高度,作为字体的 em 平方尺寸的多倍,以控制文本行的高度。有效值范围为 1.0 到 3.0,默认为 1.0。

MaxVisibleGraphemes

读取并联

此属性控制在 TextBox 上显示的最大字母数 (或文本单位),无论它是显示 TextBox.PlaceholderText 还是 TextBox.Text

更改属性不会更改可见的字母的位置或大小 - 布局将被计算为如果所有字母都可见。

将属性设置为 -1 可禁用限制并显示 TextBox.Text 的整体。

MultiLine

读取并联

当设置为真时,TextBox内的文本可以移动到多个线上。这也允许玩家使用输入键移动到新的线上。

OpenTypeFeatures

读取并联

OpenTypeFeaturesError

只读
未复制
读取并联

PlaceholderColor3

读取并联

设置在 TextBox 中还没有输入文本时使用的文本颜色。

PlaceholderText

读取并联

设置在 TextBox 中还没有输入文本时显示的文本。

RichText

读取并联

此属性决定是否使用富文本格式渲染 字符串。富文本使用简单的标记标签来格式化字符串的部分,以粗体、斜体、特定颜色等形式进行装饰。

要使用富文本,只需在 TextBox.Text 字符串中包含格式标签即可。

请注意,当 TextBox 启用此属性时,箱子获得焦点,用户可以编辑和与完整的 XML 字符串交互,包括所有的格式标签。当焦点丢失时,文本将自动解析并渲染标签为富文本。

SelectionStart

读取并联

决定文本选择的起始位置,或 -1 如果 TextBox 没有选择范围的文本。如果值为 -1 或等于 CursorPosition ,则没有选择的文本范围。该属性使用与 CursorPosition 相同的定位逻辑。选择开始将大于鼠标位置,如果鼠标位于选择的开始,小于鼠标位置,如果鼠标位于选择的结束。

代码示例

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

读取并联

如果设置为真,输入到平台的本地内容将取代 Roblox 的内置键盘。

Text

读取并联

文本属性决定了 UI 元素渲染的内容。屏幕上渲染的字符串的视觉属性由 TextBox.TextColor3 , TextBox.TextTransparency , TextBox.TextSize , TextBox.Font , TextBox.TextScaled , TextBox.TextWrapped , TextBox.TextXAlignmentTextBox.TextYAlignment 决定。

可以渲染表情符号(例如,😃)和其他符号。这些特殊符号不受 TextBox.TextColor3 属性影响。这些可以粘贴到 ScriptLocalScript 对象以及属性窗口内的字段。

该属性可能包含新行字符,但是无法在属性窗口中输入新行字符。同样,此属性可能包含标签字符,但会以空格形式渲染。

代码示例

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

只读
未复制
读取并联

只读属性 TextBounds 反映了偏移中渲染文本的绝对大小。换言之,如果你试图将文本放入长方形,这个属性将反映出你需要的长方形最小尺寸,以便将文本放入。

使用 TextService:GetTextSize() , 您可以预测 字符串extBounds 在给定文本标签上会显示什么文本边界, TextBox.Font , TextBox.TextSize 和框架大小。

代码示例

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

读取并联

该属性决定了 GuiObject 元素渲染的所有文本的颜色。这个属性以及 TextBox.Font , TextBox.TextSizeTextBox.TextTransparency 将决定文本的视觉属性。文本在文本画笔之后渲染(TextBox.TextStrokeColor3)。

文本易于由玩家阅读是很重要的!请确保选择色彩饱和度较低的颜色,例如白色、灰色或黑色。确保您的文本颜色与 UI 元素的 TextBox.BackgroundColor3 对比。如果元素有透明背景,请尝试使用黑色TextBox.TextStrokeColor3来帮助对比文本与其背后的 3D 世界。

代码示例

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

读取并联

TextEditable

读取并联

可编辑文本 决定用户是否可以通过输入更改 Text。建议在禁用此属性时禁用 ClearTextOnFocus,否则文本可能会在聚焦时清除。该属性有用于制作可在游戏中复制内容的只读 TextBox。

TextFits

只读
未复制
读取并联

文本是否适合 TextBox 的限制。

TextScaled

读取并联

而不是使用 TextScaled,我们建议您考虑使用 AutomaticSize,一种新方法来动态调整 UI,以获得最佳视觉效果。

TextScaled 属性决定是否将文本缩放以填充整个 UI 元素的空间。启用此功能时,TextBox.TextSize被忽略,TextBox.TextWrapped自动启用。此属性对于在 BillboardGuis 内渲染文本用户界面元素有用。

当此属性用于屏幕空间用户界面时,可能需要使用 UITextSizeConstraint 来限制可能的文本尺寸范围。

文本缩放和自动尺寸

建议开发人员避免使用 TextScaled 并调整 UI 以利用自动大小属性。以下是两个属性之间的核心差异:

  • 文本缩放将内容(文本)缩放到适合用户界面。如果没有仔细考虑,一些文本可能会因缩放太小而变得难以阅读。
  • 自动大小会将界面重新大小以容纳内容。

使用自动大小,您可以调整 UI 以容纳内容(文本),同时保持一致的字体大小。了解有关如何使用自动缩放的更多信息,请参阅 UI 自动缩放文章。

我们建议您不要在同一个用户界面对象上应用 TextScaled 和 AutomaticSize 两个属性。如果您应用两个属性:

  • 自动大小确定一个 GuiObject 可以使用的最大空间数量(在这种情况下是文本)
  • 文本缩放使用自动大小确定的可用空间来缩放字体大小,以适应可用空间,如果没有尺寸限制,最大字体大小(100)将扩展到最大字体大小(100)
  • 最终结果将是:文本达到 100 字体大小,UI 对象将扩展以适应该文本

同时使用自动尺寸和文本缩放可能会导致自动尺寸关闭时的缩放差异大于自动尺寸启用时。

代码示例

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

读取并联

TextSize 属性决定了一行渲染文本的抵消高度。单位是在偏移中,而不是在点上(这是大多数文档编辑程序中使用的)。“遗产”字体不拥有此属性。

代码示例

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

读取并联

TextStrokeColor3 属性设置渲染文本的stroke颜色或轮廓颜色。这个属性和 TextBox.TextStrokeTransparency 决定文本杆的视觉属性。

文本stroke在普通文本之前渲染,只是在各个方向的 +/- 1 像素偏移中的 4 个相同文本渲染。文本冲程渲染与 TextBox.TextColor3TextBox.TextTransparency 独立且相同。

代码示例

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

读取并联

文本透明属性设置渲染文本的stroke或轮廓透明度。这个属性和 TextBox.TextStrokeColor3 决定文本杆的视觉属性。

文本stroke在普通文本之前渲染,只是在各个方向的 +/- 1 像素偏移中的 4 个相同文本渲染。文本冲程渲染与 TextBox.TextColor3TextBox.TextTransparency 独立且相同。由于文本冲程是相同透明度的多个渲染,这个属性实际上是四倍增加的(例如0.5的文本冲程透明度与 0.0625 的文本透明度相当,或 0.5^4)。因此,建议将文本冲程透明度设置为 0.75 到 1 范围内的值,以获得更精致的效果。

代码示例

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

读取并联

TextColor3 属性决定了 UI 元素渲染的所有文本的透明度。这个属性以及 TextBox.Font , TextBox.TextSizeTextBox.TextColor3 将决定文本的视觉属性。文本在文本画笔之后渲染(TextBox.TextStrokeTransparency)。

使用数字循环时渐渐消失的文本是一个很好的方法,吸引玩家注意屏幕上显示的文本。


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

代码示例

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

读取并联

控制此文本框中显示的文本的截断。

TextWrapped

读取并联

启用后,该属性将在 TextBox 元素空间内的多个线上渲染文本,以便 TextBox.TextBounds 永远不会超过 GUI 元素的 GuiBase2d.AbsoluteSize

这可以通过将长条文本拆分为多个线来实现。行间空格会被首选;如果一个长而未被分割的单词超出元素宽度,该单词将被分为多个线段。

如果进一步的行分割会导致文本(TextBox.TextBounds 的 Y 组成)超过元素的垂直高度(GuiBase2d.AbsoluteSize 的 Y 组成),那条线将不会被渲染。

代码示例

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

读取并联

TextXAlignment 确定 UI 元素空间内渲染的文本的横向对齐 (X 轴)。它与 CSS 文本对齐属性相似,具有左、右和中心值(没有调整选项)。对于左侧和右侧,文本被渲染为左/右文本边界只触摸到 UI 元素矩形边缘。对于中心,每行文本都位于 UI 元素矩形的中心。

该属性与 TextBox.TextYAlignment 结合使用,可完全确定在两个轴上的文本对齐。该属性不会影响读写属性 TextBox.TextBoundsTextBox.TextFits

代码示例

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

读取并联

文本对齐确定了 UI 元素空间内渲染的文本的垂直对齐(Y 轴)。对于顶部和底部,文本被渲染为可以让顶部/底部文本边界只触碰到 UI 元素矩形边缘。对于中心,文本被渲染为从文本顶部边界到元素顶部和文本底部到元素底部的等距离。

该属性与 TextBox.TextXAlignment 结合使用,可完全确定在两个轴上的文本对齐。该属性不会影响读写属性 TextBox.TextBoundsTextBox.TextFits

代码示例

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

方法

CaptureFocus

()

强制客户端专注于文本框。


返回

()

代码示例

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

如果文本框被聚焦,返回真值;如果不是,返回错误值。


返回

ReleaseFocus

()

强制客户端关闭 TextBox 的焦点。 submitted 参数允许您在 enterPressed 事件中覆盖 TextBox.FocusLost 参数。

该项目应与 LocalScript 一起使用,以便在在线模式下按期望的方式运行。

以下显示的代码将强制客户端在选择后的 5 秒内将“文本框”解除焦点:


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

请注意,上面的例子假设它在本地脚本中,作为 TextBox 的子脚本。

参数

submitted: boolean
默认值:false

返回

()

代码示例

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)

活动

FocusLost

当客户端让其焦点离开文本框时发生火焰 - 通常是当客户端单击/点击文本框外时。这也会在 TextBox 强制关注用户时发射。

它可以与 TextBox.Focused 一起使用,追踪文本框何时获得或失去焦点。

还请参阅UserInputService.TextBoxFocusedUserInputService.TextBoxFocusReleased 以获取类似功能,其依赖于 UserInputService 服务。

此事件只会在 LocalScript 中使用时发射。

参数

enterPressed: boolean

一个指示客户端是否按下了输入键以失去焦点(true)或不是(false)的 boolean 值。

inputThatCausedFocusLoss: InputObject

一个 InputObject 实例,表示导致 TextBox 失去焦点的输入类型。


代码示例

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

TextBox 获得焦点时发生火焰 - 通常是当客户单击/点击文本框以开始文本输入时。这也会在 TextBox 强制关注用户时发射。

它可以与 TextBox.FocusLost 一起使用,追踪文本框何时获得或失去焦点。

还请参阅UserInputService.TextBoxFocusedUserInputService.TextBoxFocusReleased 以获取类似功能,其依赖于 UserInputService 服务。

此事件只会在 LocalScript 中使用时发射。


代码示例

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