包含此页的版本:
不含此页的版本:
版本: 2021.3+
此示例演示如何使用样式在滚动视图中包装内容。出于演示目的,本指南适用于编辑器UI。但是,有关设置滚动视图样式的说明也适用于运行时 UI。
此示例创建具有两个滚动视图的自定义编辑器窗口:
若要在滚动视图中换行标签的文本,请将样式应用于 Label 控件,并使用 VisualElement 来保存标签。
要将元素包装在滚动视图中,请将样式应用于滚动视图的内容容器。
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
要尝试此示例,请首先创建一个包含一些默认内容的自定义编辑器窗口。
ScrollViewExample.ScrollViewExample.cs,ScrollViewExample.uxml和ScrollViewExample.uss.在UI文档(UXML文件)中定义基本的滚动视图结构,设置视觉元素实例化或派生自 C# 的可视化树的节点VisualElement类。您可以设置外观样式、定义行为并将其作为 UI 的一部分显示在屏幕上。更多信息
请参阅术语表,并在 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);
}
}
}
要测试滚动视图换行,请从菜单中选择示例> ScrollView 换行示例。