版本:2021.3+
此示例将演示如何使用样式将内容放在滚动视图中。出于演示目的,本指南适用于编辑器__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary。但是,有关为滚动视图设置样式的说明也适用于运行时 UI。
此示例创建了一个具有两个滚动视图的自定义编辑器窗口:
为了让标签中的文本在滚动视图内自动换行,您需要为标签控件应用样式,并使用一个 VisualElement 来容纳标签。
要在滚动视图内自动换行元素,为滚动视图的内容容器应用样式。
可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
要尝试该示例,请先创建一个包含一些默认内容的自定义编辑器窗口。
ScrollViewExample。ScrollViewExample.cs、ScrollViewExample.uxml 和 ScrollViewExample.uss。在 UI 文档(UXML 文件)中定义基本滚动视图结构,在 USS 文件中设置视觉元素的样式,并在 C# 脚本的第二个滚动视图中添加 15 个按钮。
将 ScrollViewExample.uxml 的内容替换为以下内容:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<Style src="ScrollViewExample.uss" />
<ui:ScrollView>
<ui:VisualElement>
<ui:Label text="ScrollView Wrapping Example" />
</ui:VisualElement>
</ui:ScrollView>
<ui:ScrollView name="scroll-view-wrap-example" />
</ui:UXML>
将 ScrollViewExample.uss 的内容替换为以下内容:
Label {
font-size: 20px;
-unity-font-style: bold;
color: rgb(68, 138, 255);
/* Style to wrap text of the label */
white-space: normal;
}
/* Style to wrap elements inside the scroll view */
#scroll-view-wrap-example .unity-scroll-view__content-container {
flex-direction: row;
flex-wrap: wrap;
}
Button {
width: 50px;
height: 50px;
}
将 ScrollViewExample.cs 的内容替换为以下内容:
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
public class ScrollViewExample : EditorWindow
{
[MenuItem("Example/ScrollView Wrapping Example")]
public static void ShowExample()
{
var wnd = GetWindow<ScrollViewExample>();
}
public void CreateGUI()
{
// Each editor window contains a root VisualElement object.
VisualElement root = rootVisualElement;
// Import UXML.
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/ScrollViewExample.uxml");
VisualElement ScrollViewExample = visualTree.Instantiate();
root.Add(ScrollViewExample);
// Find the scroll view by name.
VisualElement scrollview = root.Query<ScrollView>("scroll-view-wrap-example");
// Add 15 buttons inside the scroll view.
for (int i = 0; i < 15; i++)
{
Button button = new Button();
button.text = "Button";
scrollview.Add(button);
}
}
}
要测试滚动视图的自动换行,请从菜单中选择示例 (Example) > ScrollView 换行示例 (ScrollView Wrapping Example)。