TextBox

Tampilkan yang Tidak Digunakan Lagi

*Konten ini diterjemahkan menggunakan AI (Beta) dan mungkin mengandung kesalahan. Untuk melihat halaman ini dalam bahasa Inggris, klik di sini.

Sebuah Kotak Teks memungkinkan pemain untuk memberikan input teks.Ini berperilaku serupa dengan TextButton , kecuali bahwa Kotak Teks tunggal dapat dibawa ke fokus dengan mengklik, mengetuk atau pemilihan gamepad.Sementara fokus, pemain dapat menggunakan keyboard untuk mengubah properti Text.

  • Jika tidak ada teks, PlaceholderText akan terlihat. Ini berguna mengingatkan pemain jenis atau format data yang harus mereka masukkan.
  • Secara default, properti ClearTextOnFocus diaktifkan dan memastikan tidak ada teks yang ada saat TextBox difokuskan.Ini mungkin tidak diinginkan untuk teks yang harus dapat diedit oleh pemain.
  • Properti MultiLine memungkinkan pemain untuk memasukkan beberapa baris teks dengan karakter baris baru ( \n ).

The ContextActionService menghormati keybind TextBox dan akan secara otomatis mencegah tekanan tombol dikirim ke tindakan yang terikat dengan ContextActionService:BindAction() .UserInputService.InputBegan dan peristiwa terkait masih akan terbakar saat TextBox berada dalam fokus.

Fokuskan Negara

Dimungkinkan untuk mendeteksi dan mengubah status fokus TextBox:

  • Anda dapat menggunakan CaptureFocus ketika dialog muncul sehingga pemain tidak perlu mengklik Kotak Teks saat tersedia; Anda dapat menggunakan ContextActionService:BindAction() untuk mengikat kunci tertentu untuk memfokuskan Kotak Teks menggunakan fungsi ini.Ketika Kotak Teks masuk ke fokus, acara Focused terjadi.
  • Anda dapat mendeteksi apakah Kotak Teks tertentu berada dalam fokus dengan menggunakan IsFocused . Alternatifnya, UserInputService:GetFocusedTextBox() dapat digunakan untuk memeriksa apakah ada Kotak Teks yang berada dalam fokus.
  • Ketika pemain selesai memasukkan teks, acara FocusLost terjadi, menunjukkan apakah pengguna menekan Enter untuk mengirimkan teks bersama dengan InputObject yang menyebabkan hilangnya fokus.Saat menggunakan keyboard di layar pada perangkat seluler dan konsol, ReturnPressedFromOnScreenKeyboard mungkin juga terbakar.
  • Jika beberapa masalah yang lebih penting muncul selama gameplay, Anda dapat ReleaseFocus dari Kotak Teks sehingga input keyboard pemain kembali ke game Anda.

Editasi Teks

Kotak Teks mendukung pemilihan teks melalui properti CursorPosition dan SelectionStart nya.Menggunakan GetPropertyChangedSignal , Anda dapat mendeteksi kapan perubahan seleksi terjadi.Selain itu, adalah mungkin bagi pemain untuk menyalin dan menempelkan teks di dalam Kotak Teks, memungkinkan dukungan klip dasar.

Pemberitahuan Penyaringan Teks Permainan yang memudahkan komunikasi antar pemain menggunakan teks, seperti obrolan khusus atau tag nama, harus memfilter teks tersebut dengan benar menggunakan TextService:FilterStringAsync() atau Chat:FilterStringAsync() .Jika ini tidak dilakukan dengan benar, permainan Anda dapat menerima actionmoderasi.

Contoh Kode

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)

Rangkuman

Properti

Properti diwarisi dari GuiObjectProperti diwarisi dari GuiBase2d

Metode

Metode diwarisi dari GuiObject

Acara

Acara diwarisi dari GuiObjectAcara diwarisi dari GuiBase2d

Properti

ClearTextOnFocus

Baca Paralel

Menentukan apakah mengklik di TextBox akan menghapus propertinya TextBox.Text

ContentText

Hanya Baca
Tidak Direplikasi
Baca Paralel

CursorPosition

Baca Paralel

Properti ini menentukan offset kursor teks dalam bayt, atau -1 jika TextBox saat ini tidak sedang diedit.Nilai 1 mewakili posisi sebelum byte pertama di properti Text.Ketika digunakan bersama dengan properti SelectionStart , adalah mungkin untuk mendapatkan dan mengatur teks yang dipilih dalam TextBox .

Perhatikan bahwa unit properti ini adalah byte dan bahwa banyak karakter unicode seperti emoji lebih dari 1 byte.Sebagai kejadian, jika pemain mengetik "Hello👋" ("Hello" segera diikuti dengan tanda tangan tangan bergoyang), posisi kursor akan menjadi 10 , bukan 7 , karena emoji menggunakan 4 bayt.

Contoh Kode

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)
Tersembunyi
Tidak Direplikasi
Baca Paralel

Properti Font memilih salah satu dari beberapa yang sudah didefinisikan fonts dengan mana elemen UI akan menampilkan teksnya.Beberapa font memiliki varian berani, italik, dan/atau ringan (karena tidak ada properti berat huruf atau gaya huruf).

Dengan pengecualian font "Legacy", setiap font akan menampilkan teks dengan ketinggian baris sama dengan properti TextBox.TextSize.Font "Kode" adalah satu-satunya font monospace.Ini memiliki properti unik yang setiap karakter memiliki rasio lebar dan tinggi yang sama persis dari 1:2.Lebar setiap karakter sekitar setengah dari properti TextBox.TextSize .

Properti ini disinkronkan dengan properti TextBox.FontFace . Saat mengatur Font, FontFace akan diatur ke Font.fromEnum(value) .

Contoh Kode

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

Baca Paralel

Properti FontFace mirip dengan properti Font, tetapi memungkinkan mengatur font yang tidak ada di enum Font.

Properti ini disinkronkan dengan properti TextBox.Font .Saat mengatur FontFace, Font diatur ke nilai enum yang sesuai, atau ke Enum.Font.Unknown jika tidak ada pertandingan.

LineHeight

Baca Paralel

Mengontrol ketinggian baris, sebagai pengganda ukuran em kotak huruf, dengan menyesuaikan jarak antara baris teks di TextBox .Nilai yang valid berkisar dari 1.0 hingga 3.0, dengan default ke 1.0.

MaxVisibleGraphemes

Baca Paralel

Properti ini mengontrol jumlah maksimum grafem (atau unit teks) yang ditampilkan di TextBox, terlepas dari apakah itu menunjukkan TextBox.PlaceholderText atau TextBox.Text.

Mengubah properti tidak mengubah posisi atau ukuran huruf yang terlihat - tata letak akan dihitung seolah-olah semua huruf terlihat.

Mengatur properti ke -1 menonaktifkan batas dan menunjukkan seluruhnya dari TextBox.Text .

MultiLine

Baca Paralel

Saat diatur ke benar, teks di dalam Kotak Teks dapat dipindahkan ke banyak baris. Ini juga memungkinkan pemain untuk menggunakan tombol enter untuk berpindah ke baris baru.

OpenTypeFeatures

Baca Paralel

OpenTypeFeaturesError

Hanya Baca
Tidak Direplikasi
Baca Paralel

PlaceholderColor3

Baca Paralel

Mengatur warna teks yang digunakan saat belum ada teks yang dimasukkan ke TextBox.

PlaceholderText

Baca Paralel

Mengatur teks yang ditampilkan saat belum ada teks yang dimasukkan ke TextBox.

RichText

Baca Paralel

Properti ini menentukan apakah TextBox menampilkan string TextBox.Text menggunakan format teks kaya.Teks kaya menggunakan tag penandaan sederhana untuk menyoroti bagian string dalam huruf tebal, italik, warna spesifik, dan banyak lagi.

Untuk menggunakan teks kaya, cukup masukkan tag formatasi dalam string TextBox.Text.

Perhatikan bahwa ketika TextBox memiliki properti ini diaktifkan dan kotak mendapatkan fokus, pengguna akan dapat mengedit dan berinteraksi dengan string XML lengkap, termasuk semua tag formatasi.Ketika fokus hilang, teks akan secara otomatis menguraikan dan menampilkan tag sebagai teks kaya.

SelectionStart

Baca Paralel

Menentukan posisi awal pemilihan teks, atau -1 jika TextBox tidak memiliki rentang teks yang dipilih.Jika nilainya adalah -1 atau setara dengan CursorPosition , tidak ada rentang teks yang dipilih.Properti ini menggunakan logika penempatan yang sama dengan CursorPosition.Pemilihan Mulai akan lebih besar dari CursorPosition jika kursor berada di awal seleksi, dan kurang dari CursorPosition jika kursor berada di akhiri.

Contoh Kode

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

Baca Paralel

Jika diatur ke benar, input asli ke platform digunakan sebagai gantinya keyboard bawaan Roblox.

Text

Baca Paralel

Properti Teks menentukan konten yang ditampilkan oleh elemen UI.Properti visual string yang ditampilkan di layar ditentukan oleh TextBox.TextColor3 , TextBox.TextTransparency , TextBox.TextSize , TextBox.Font , TextBox.TextScaled , TextBox.TextWrapped , TextBox.TextXAlignment dan TextBox.TextYAlignment.

Dimungkinkan untuk menampilkan emoji (misalnya, 😃) dan simbol lainnya.Simbol khusus ini tidak terpengaruh oleh properti TextBox.TextColor3.Ini dapat disisipkan ke dalam Script dan LocalScript objek, serta bidang di jendela Properti.

Properti ini dapat berisi karakter baris baru, namun tidak mungkin untuk mengetik karakter baris baru di jendela Properti.Demikian pula, properti ini dapat berisi karakter tab, tetapi akan ditampilkan sebagai ruang sebagai gantinya.

Contoh Kode

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

Hanya Baca
Tidak Direplikasi
Baca Paralel

Properti baca hanya TextBounds mencerminkan ukuran absolut teks yang diterjemahkan dalam offset.Dengan kata lain, jika Anda mencoba untuk memasukkan teks ke dalam segi empat, properti ini akan mencerminkan dimensi minimum segi empat yang Anda butuhkan untuk memasukkan teks.

Menggunakan TextService:GetTextSize() , Anda dapat memprediksi apa yang akan menjadi Batas Teks pada Label Teks yang diberikan string, TextBox.Font , TextBox.TextSize dan ukuran frame.

Contoh Kode

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

Baca Paralel

Properti ini menentukan warna semua teks yang ditampilkan oleh elemen GuiObject .Properti ini bersama dengan TextBox.Font , TextBox.TextSize dan TextBox.TextTransparency akan menentukan properti visual teks.Teks ditampilkan setelah garis teks ( TextBox.TextStrokeColor3 ).

Penting agar teks mudah dibaca oleh pemain! Pastikan untuk memilih warna dengan sedikit hingga tidak ada saturasi, seperti putih, abu-abu, atau hitam.Pastikan warna teks Anda kontras dengan TextBox.BackgroundColor3 elemen UI.Jika elemen memiliki latar belakang transparan, coba gunakan hitam TextBox.TextStrokeColor3 untuk membantu mengkontras teks dengan dunia 3D di belakangnya.

Contoh Kode

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

Baca Paralel

TextEditable

Baca Paralel

TextEditable menentukan apakah pengguna dapat mengubah Text melalui input.Disarankan untuk menonaktifkan ClearTextOnFocus ketika properti ini dinonaktifkan, jika tidak, Teks bisa dihapus saat fokus.Properti ini berguna untuk membuat Kotak Teks hanya dibaca dari mana konten dapat disalin dalam game.

TextFits

Hanya Baca
Tidak Direplikasi
Baca Paralel

Apakah teks sesuai dengan batasan TextBox.

TextScaled

Baca Paralel

Daripada menggunakan TextScaled, kami sarankan Anda mempertimbangkan menggunakan AutomaticSize, metode baru untuk mengubah ukuran UI secara dinamis yang akan memberi Anda hasil visual terbaik yang mungkin.

Properti TextScaled menentukan apakah teks diperbesar sehingga mengisi seluruh ruang elemen UI.Ketika ini diaktifkan, TextBox.TextSize diabaikan dan TextBox.TextWrapped diaktifkan secara otomatis.Properti ini berguna untuk elemen UI penyajian teks dalam BillboardGuis .

Ketika properti ini digunakan untuk UI ruang layar, mungkin diinginkan untuk menggunakan UITextSizeConstraint untuk membatasi rentang ukuran teks yang mungkin.

Skala Teks dan Ukuran Otomatis

Disarankan agar pengembang menghindari penggunaan TextScaled dan menyesuaikan UI untuk memanfaatkan properti AutomaticSize sebagai gantinya.Berikut adalah perbedaan inti antara dua properti:

  • TextScaled menyesuaikan konten (teks) untuk menampung UI. Tanpa pertimbangan hati-hati, beberapa teks mungkin menjadi tidak dapat dibaca jika diperkecil terlalu kecil.
  • Ukuran Otomatis mengubah UI untuk menampung konten.

Dengan Ukuran Otomatis, Anda dapat menyesuaikan UI untuk menampung konten (teks) sambil menjaga ukuran font yang konsisten.Untuk informasi lebih lanjut tentang cara menggunakan ukuran otomatis, lihat artikel UI Ukuran Otomatis.

Kami sarankan agar Anda tidak menerapkan kedua TextScaled dan AutomaticSize pada objek UI yang sama. Jika Anda menerapkan kedua properti:

  • Ukuran Otomatis menentukan jumlah maksimum ruang yang tersedia yang dapat digunakan oleh GuiObject (dalam kasus ini, teks)
  • TextScaled menggunakan ruang yang tersedia yang ditentukan oleh AutomaticSize, untuk menyesuaikan ukuran font agar sesuai dengan ruang yang tersedia, yang akan diperluas hingga ukuran maksimum font (100), jika tidak ada batasan ukuran
  • Hasil akhirnya akan menjadi: teks pergi ke ukuran 100 font dan objek UI akan diperluas untuk sesuai dengan teks itu

Menggunakan kedua ukuran otomatis dan skala teks pada saat yang sama dapat menyebabkan perbedaan skala yang signifikan daripada saat AutomaticSize dimatikan.

Contoh Kode

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

Baca Paralel

Properti TextSize menentukan ketinggian dalam offset dari satu baris teks yang diterjemahkan.Unit berada dalam offset, bukan titik (yang digunakan dalam sebagian besar program pengeditan dokumen).Font "Legacy" tidak memiliki properti ini.

Contoh Kode

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

Baca Paralel

Properti TextStrokeColor3 menetapkan warna stroke, atau garis, dari teks yang diterjemahkan.Properti ini dan TextBox.TextStrokeTransparency menentukan properti visual dari garis teks.

Stroke teks ditampilkan sebelum teks normal dan hanya merupakan 4 rendering teks yang sama dalam +/- 1 penggeseran piksel di setiap arah.Rendering garis teks bekerja secara independen dan identik dengan TextBox.TextColor3 dan TextBox.TextTransparency .

Contoh Kode

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

Baca Paralel

Properti TextStrokeTransparency menetapkan transparansi stroke, atau garis, dari teks yang diterjemahkan.Properti ini dan TextBox.TextStrokeColor3 menentukan properti visual dari garis teks.

Stroke teks ditampilkan sebelum teks normal dan hanya merupakan 4 rendering teks yang sama dalam +/- 1 penggeseran piksel di setiap arah.Rendering garis teks bekerja secara independen dan identik dengan TextBox.TextColor3 dan TextBox.TextTransparency .Karena garis teks hanyalah beberapa representasi dari transparansi yang sama, properti ini pada dasarnya adalah multiplikatif pada dirinya sendiri empat kali lipat (misalnyaTransparansi Stroke Teks 0,5 muncul sekitar sama dengan Transparansi Teks 0,0625, atau 0,5^4).Oleh karena itu, disarankan untuk mengatur Transparansi Garis Teks ke nilai dalam rentang 0,75 hingga 1 untuk efek yang lebih halus.

Contoh Kode

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

Baca Paralel

Properti TextColor3 menentukan transparansi semua teks yang ditampilkan oleh elemen UI.Properti ini bersama dengan TextBox.Font , TextBox.TextSize dan TextBox.TextColor3 akan menentukan properti visual teks.Teks ditampilkan setelah garis teks ( TextBox.TextStrokeTransparency ).

Teks memudar saat menggunakan loop for numerik adalah cara fantastis untuk menarik perhatian pemain ke teks yang muncul di layar.


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

Contoh Kode

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

Baca Paralel

Mengontrol pemotongan teks yang ditampilkan di TextBox ini.

TextWrapped

Baca Paralel

Saat diaktifkan, properti ini akan menampilkan teks di beberapa baris dalam ruang elemen TextBox sehingga TextBox.TextBounds tidak akan pernah melebihi GuiBase2d.AbsoluteSize elemen GUI.

Ini dicapai dengan memecahkan baris teks panjang menjadi beberapa baris.Pemutusan baris akan lebih memilih spasi kosong; jika kata panjang yang tidak diputus melebihi lebar elemen, kata itu akan dipatahkan menjadi beberapa baris.

Jika lini berikutnya rusak akan menyebabkan ketinggian vertikal teks (komponen Y dari TextBox.TextBounds) melebihi ketinggian vertikal elemen (komponen Y dari GuiBase2d.AbsoluteSize) maka baris itu tidak akan ditampilkan sama semua.

Contoh Kode

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

Baca Paralel

TextXAlignment menentukan alineasi horizontal (X-axis) teks yang ditampilkan dalam ruang elemen UI.Ini berfungsi serupa dengan properti aline teks CSS, dengan nilai kiri, kanan, dan tengah (tidak ada opsi justifikasi).Untuk Kiri dan Kanan, teks ditampilkan sehingga batas teks kiri/kanan hanya menyentuh ujung elemen UI.Untuk Pusat, setiap baris teks ditempatkan di tengah bagian UI elemen segi.

Properti ini digunakan bersama dengan TextBox.TextYAlignment untuk sepenuhnya menentukan alineasi teks di kedua sumbu.Properti ini tidak akan memengaruhi properti hanya dibaca TextBox.TextBounds dan TextBox.TextFits.

Contoh Kode

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

Baca Paralel

Penyesuaian Teks menentukan alineasi vertikal (sumbu Y) dari teks yang ditampilkan dalam ruang elemen UI.Untuk Atas dan Bawah, teks ditampilkan sehingga batas teks atas/bawah hanya menyentuh ujung elemen UI.Untuk Pusat, teks ditampilkan sehingga ada ruang yang sama dari batas atas teks ke bagian atas elemen dan batas bawah teks ke bagian bawah elemen.

Properti ini digunakan bersama dengan TextBox.TextXAlignment untuk sepenuhnya menentukan alineasi teks di kedua sumbu.Properti ini tidak akan memengaruhi properti hanya dibaca TextBox.TextBounds dan TextBox.TextFits.

Contoh Kode

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

Metode

CaptureFocus

()

Memaksa klien untuk fokus pada TextBox.


Memberikan nilai

()

Contoh Kode

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

Kembalikan benar jika kotak teks difokuskan, atau salah jika tidak.


Memberikan nilai

ReleaseFocus

()

Memaksa klien untuk tidak fokus pada TextBox. Parameternya submitted memungkinkan Anda untuk menggantikan parameter enterPressed dalam acara TextBox.FocusLost.

Item ini harus digunakan dengan LocalScript untuk berfungsi seperti yang diharapkan dalam mode online.

Kode yang ditunjukkan di bawah ini akan memaksa klien untuk tidak fokus pada 'TextBox' 5 detik setelah dipilih:


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

Harap diperhatikan bahwa contoh di atas mengasumsikan bahwa itu ada di LocalScript, sebagai anak dari TextBox.

Parameter

submitted: boolean
Nilai Default: false

Memberikan nilai

()

Contoh Kode

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)

Acara

FocusLost

Melepaskan api saat klien membiarkan fokus mereka meninggalkan TextBox - biasanya saat klien mengklik/mengetuk di luar TextBox.Ini juga menembak jika TextBox memaksa fokus pada pengguna.

Ini dapat digunakan bersama dengan TextBox.Focused untuk melacak ketika TextBox mendapatkan dan kehilangan fokus.

Lihat juga UserInputService.TextBoxFocused dan UserInputService.TextBoxFocusReleased untuk fungsi serupa yang bergantung pada layanan UserInputService.

Peristiwa ini hanya akan terbakar saat digunakan dalam LocalScript .

Parameter

enterPressed: boolean

A boolean yang menunjukkan apakah klien menekan Enter untuk kehilangan fokus ( benar ) atau tidak ( salah ).

inputThatCausedFocusLoss: InputObject

Sebuah instansi InputObject menunjukkan jenis input yang menyebabkan TextBox kehilangan fokus.


Contoh Kode

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

Memicu ketika TextBox mendapatkan fokus - biasanya ketika klien mengklik/mengetuk kotak teks untuk memulai masukan teks.Ini juga menembak jika TextBox memaksa fokus pada pengguna.

Ini dapat digunakan bersama dengan TextBox.FocusLost untuk melacak ketika TextBox mendapatkan dan kehilangan fokus.

Lihat juga UserInputService.TextBoxFocused dan UserInputService.TextBoxFocusReleased untuk fungsi serupa yang bergantung pada layanan UserInputService.

Peristiwa ini hanya akan terbakar saat digunakan dalam LocalScript .


Contoh Kode

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