TextBox

顯示已棄用項目

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

一個 文字框 允許玩家提供文字輸入。它的行為類似於 TextButton ,除了單個文字框可以通過點擊、點擊或遊戲控制板選擇來獲得焦點。當在焦點上時,玩家可以使用鍵盤來變更 Text 屬性。

  • 如果沒有文字,PlaceholderText將會顯示。這有助於提醒玩家輸入的數據種類或格式。
  • 預設情況下,ClearTextOnFocus屬性是啟用的,並確保在TextBox焦點時沒有現有文字。這可能不適合玩家可以編輯的文字。
  • MultiLine屬性允許玩家輸入多行文字,包括新行字符(\n)。

The ContextActionService 榮譽 TextBox 鍵綁和將自動防止鍵按事件傳送到具有 ContextActionService:BindAction() 綁定的行動。UserInputService.InputBegan 和相關事件仍會在文字框在焦點時發射。

專注狀態

可以偵測並更改 TextBox 的焦點狀態:

  • 當對話框出現時,您可以使用 CaptureFocus 以便玩家不需要單擊文字框當它可用時;您可以使用 ContextActionService:BindAction() 將某個鍵綁定到聚焦文字框使用此函數。當文字框進入焦點時,Focused發生。
  • 您可以使用 IsFocused 來偵測特定的文字框是否正在聚焦。或者,UserInputService:GetFocusedTextBox() 可以用來檢查是否有任何文字框正在聚焦。
  • 當玩家輸入文字完成時,事件發生,表示如果用戶按下了輸入文字以及導致失去焦點的導致,用戶按下了導致。當在手機和控制台上使用屏幕鍵盤時,ReturnPressedFromOnScreenKeyboard 也可能發觸發。
  • 如果在遊玩過程中出現更重要的問題,您可以ReleaseFocus文字框,以便玩家的輸入返回到您的遊戲。

文字編輯

文字框支持通過其 CursorPositionSelectionStart 屬性選擇文字。使用 GetPropertyChangedSignal ,您可以偵測當選擇變更時。此外,玩家還可以在文字框內複製並粘貼文字,啟用基本剪貼協助。

文字過濾通知 使用文字進行玩家對玩家通信的遊戲,例如自訂聊天或名稱標籤,必須使用 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

平行讀取

字體面屬性與字體屬性相似,但允許設置不存在於字體枚列中的字體。

此屬性與 TextBox.Font 屬性保持同步。當設置字體時,字體將設為對應的枚疊值或 Enum.Font.Unknown 如果沒有匹配。

LineHeight

平行讀取

控制線的高度,作為字體的 em 平方尺寸的倍數,通過在 TextBox 中調整文字線之間的間距來控制線的高度。有效值範圍為 1.0 到 3.0,預設為 1.0。

MaxVisibleGraphemes

平行讀取

此屬性控制在 TextBox 上顯示的最大字元數 (或文字單位),無論是顯示 TextBox.PlaceholderTextTextBox.Text

更改屬性不會更改可見的字元位置或尺寸 - 布局將計算為所有字元都可見的情況。

將屬性設為 -1 會禁用限制並顯示 TextBox.Text 的整體。

MultiLine

平行讀取

當設為真實時,文字盒內的文字可以移動到多個線條。這也讓玩家可以使用輸入鍵移動到新的線條。

OpenTypeFeatures

平行讀取

OpenTypeFeaturesError

唯讀
未複製
平行讀取

PlaceholderColor3

平行讀取

設置在TextBox尚未輸入文字時使用的文字顏色。

PlaceholderText

平行讀取

設置在TextBox尚未輸入文字時顯示的文字。

RichText

平行讀取

此屬性決定是否使用 TextBox 富文本格式來渲染 TextBox.Text 字串。富文本使用簡單的標記標籤來格式化字串的部分,以粗體、斜體、特定顏色等形式。

要使用豐富的文字,只需在 TextBox.Text 字串中包含格式標籤即可。

注意,當 TextBox 有此特性啟用時,箱子獲得焦點時,使用者將能夠編輯和與完整的 XML 字串互動,包括所有的格式標籤。當焦點遺失時,文字會自動解析並渲染標籤為富文本。

SelectionStart

平行讀取

決定文字選擇的起始位置,或 -1 如果文字框沒有選擇的文字範圍。如果值是 -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() ,您可以預測給定文字標籤的字串、TextBox.Font 和框架尺寸時,TextBounds 將是什麼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.FontTextBox.TextSizeTextBox.TextTransparency 將決定文本的視覺屬性。文字會在文字輪廓之後渲染(TextBox.TextStrokeColor3)。

文字容易讓玩家讀取是很重要的!請確保選擇淺至無飽和度的顏色,例如白色、灰色或黑色。請確保文字的顏色與介面元素的 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,否則文字可能會在聚焦時清除。此屬性有助於製作只能閱讀的文字框,其中內容可以在遊戲中複製。

TextFits

唯讀
未複製
平行讀取

文字是否符合 TextBox 的限制。

TextScaled

平行讀取

而不是使用 TextScaled,我們建議您考慮使用 AutomaticSize,一種新方法來動態調整 UI,以獲得最佳視覺效果。

TextScaled 屬性決定是否將文字縮放至整個介面元素的空間。啟用此功能時,TextBox.TextSize被忽略,而TextBox.TextWrapped則自動啟用。此屬性對於在 BillboardGuis 內渲染文字的用戶介面元素有用。

當此屬性用於屏幕空間介面時,可能需要使用 UITextSizeConstraint 來限制可能的文字尺寸範圍。

文字縮放和自動尺寸

建議開發人員避免使用 TextScaled 並調整介面以利用自動尺寸屬性。以下是兩個屬性之間的核心差異:

  • 文字縮放會將內容(文字)縮放以容納介面。如果沒有仔細考慮,一些文字可能會因縮放過小而變得難以讀取。
  • 自動尺寸會將介面重新配置以容納內容。

使用自動尺寸,您可以調整您的用戶介面以容納內容(文字),同時保持一致的字體尺寸。要了解有關如何使用自動縮放的更多信息,請參閱介面自動尺寸文章。

我們建議您不要在同一個使用者介面對物件上應用 TextScaled 和 AutomaticSize 兩個屬性。如果您應用兩個屬性:

  • 自動尺寸決定 GuiObject 可使用的最大空間數量 (在這個例子中,是文字)
  • 文字縮放使用自動尺寸所決定的可用空間來將字體尺寸縮放到可用空間,這將擴展到最大字體尺寸(100),如果沒有尺寸限制
  • 最終結果將是:文字會增加到 100 字體大小,並且介面對象會擴展以容納該文字

同時使用自動尺寸和文字縮放量時,可能會比自動尺寸關閉時產生更大的縮放差異。

範例程式碼

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

平行讀取

文字尺寸屬性決定一行渲染文字的抵消高度。單位是在偏移中,而不是點(這是大多數文件編輯程序使用的)。「傳承」字體沒有這個屬性。

範例程式碼

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 屬性設置渲染的文字筆或外部線的顏色。此屬性和 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

平行讀取

文字綫條透明度屬性設置渲染的文字綫條或外部線的透明度。此屬性和 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.FontTextBox.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

平行讀取

文字對齊決定在介面元素空間內渲染的文字的垂直對齊(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

()

強制客戶專注在 TextBox 上。


返回

()

範例程式碼

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 秒鐘將「TextBox」解除焦點:


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

請注意,以上範例假設它在本地腳本中,作為文字框的兒子。

參數

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

一個是否指示客戶按下 Enter 以失去焦點(true)或不(false)的 boolean 值。

inputThatCausedFocusLoss: InputObject

一個 InputObject 示例指示了導致文字框失去焦點的輸入類型。


範例程式碼

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