cocosCreator 之 ScrollView的基本使用

2023-11-11 15:20

本文主要是介绍cocosCreator 之 ScrollView的基本使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

版本:3.4.0

语言:TypeScript

环境: Mac

参考:


简介


ScrollView组件作为滚动容器来使用,它的实现通过ScrollBar组件来展示内容的位置和Mask组件显示指定区域,来保证有限的区域内显示更多的内容。

在cocosCreator中,滚动容器的实现主要是:ScrollView组件。层级管理器的节点如下:

请添加图片描述

构成主要有两部分:

  • scrollBar 滚动条相关,用于展示内容的位置,编译器默认垂直
  • view 内容显示相关,节点内增加了Mask遮罩显示指定区域,通过content增加item显示滚动区域

ScrollView节点属性:

请添加图片描述

属性功能说明
Horizontal布尔值,是否允许横向滚动
HorizontalScrollBar节点引用,用来创建一个滚动条来显示 content 在水平方向上的位置
Vertical布尔值,是否允许纵向滚动
VerticalScrollBar节点引用,用来创建一个滚动条来显示 content 在垂直方向上的位置
Inertia滚动的时候是否有加速度
Brake滚动之后的减速系数,范围[0, 1]。 1 时立马停止滚动, 0时则会一直滚动到 content 的边界
Elastic布尔值,是否回弹
BounceDuration回弹所需要的时间,范围[0, 10]
Content节点引用,所有的子节点放到此处,必须存在,否则滚动容器无法实现
ScrollEvents可用于添加一个Target、Component、handler、 CutomEventData的回调事件
CancelInnerEvents滚动行为是否会取消子节点上注册的触摸事件,默认为 true

在cocosCreator中, 滚动容器的使用主要就是:ScrollViewPageView

滚动条
滚动视图
页面视图
ViewGroup
Component
ScrollBar
ScrollView
PageView

没有像cocos2d-x所谓的ListViewTableView 的实现,因此很多项目会对ScrollView进行二次封装,用于实现类似于TableView的功能,降低内存占用。


基本使用


使用ScrollView,需要注意:

  • scrollBar节点可选,可以通过Horizontal/HorizontalScrollBarVertical/VerticalScrollBar设置水平或垂直滚动条相关,如果不需要,可以去掉勾选或者直接删除节点
  • ScrollView节点内可以增加widget组件,用于排版使用
  • content节点内可增加Layout组件,用于设置水平,垂直,格子布局等,但注意: 不要同时使用Layout和Widget组件,以免产生不可预料的后果

针对于content下的布局组件Layout的设置,如下图:
请添加图片描述

注意设置:

  • Type 设置水平,垂直,格子布局类型
  • ResizeMode 一般设置为CONTAINER模式,它会自动计算布局的大小,用于滚动使用
  • SpacingX/SpacingY 设置item之间的间隔

设置结束后,在脚本中我们可编写如下代码完成ScrollView的基本使用:

@ccclass('UI_DemoLayer')
export class UI_DemoLayer extends Component {// 获取ScrollView组件@property(ScrollView) scroll: ScrollView = null;// 获取预制体item@property(Prefab) itemPrefab: Prefab = null;protected onLoad(): void {// 移除content下的子节点this.scroll.content.removeAllChildren();for (let i = 0; i < 10; ++i) {// 克隆并将节点添加到content中let itemNode = instantiate(this.itemPrefab);if (itemNode) {itemNode.parent = this.scroll.content;// 更新指定的itemlet itemScript = itemNode.getComponent(ScrollItem);itemScript.updateItem(i);}}}
}

在构建item前,建议调用content.removeAllChildren()接口,用于移除无效节点。

拓展

使用滚动容器,尤其在content节点内增加 Layout组件 可以很方便的设置滚动的各种类型。

下面的示例是通过脚本代码动态设置滚动视图的各种布局类型,示意图如下:
请添加图片描述

关于Toggle的使用,可参考博客: Toggle和ToggleContainer的使用。具体的实现代码:

// 布局类型
enum kLayoutType {HORIZONTAL = 0,        // 水平布局VERTICAL,              // 垂直布局GRID,                  // 格子布局
};/*
1. 预制体的大小会随着布局类型的改变而改变,主要用于Demo的实现
2. 为方便预览,水平或垂直布局item数量10个,格子布局为30个
*/
@ccclass('UI_ScrollEffecNormaltLayer')
export class UI_ScrollEffecNormaltLayer extends Component {// 滚动容器@property(ScrollView) scroll: ScrollView = null; // 预制体@property(Prefab) itemPrefab: Prefab = null; // 布局类型private _layoutType: kLayoutType = kLayoutType.HORIZONTAL;// 可视图大小private _scrollSize = null;protected start(): void {this._scrollSize = this.scroll.getComponent(UITransform).contentSize;this.refreshScroll();}// 更新scrollprivate refreshScroll() {let itemCount = 10;const content = this.scroll.content;const contentLayout = content.getComponent(Layout);const contentTransform = content.getComponent(UITransform);// 设置滚动if (this._layoutType === kLayoutType.VERTICAL) {this.scroll.horizontal = true;this.scroll.vertical = false;}else {this.scroll.horizontal = false;this.scroll.vertical = true;}// 设置布局相关if (this._layoutType === kLayoutType.VERTICAL) {contentLayout.horizontalDirection = Layout.HorizontalDirection.LEFT_TO_RIGHT;contentLayout.type = Layout.Type.HORIZONTAL;// 垂直布局固定可视区域的高度contentTransform.height = this._scrollSize.height;contentLayout.spacingX = 10;contentLayout.spacingY = 0;}else if (this._layoutType === kLayoutType.HORIZONTAL) {contentLayout.verticalDirection = Layout.VerticalDirection.TOP_TO_BOTTOM;contentLayout.type = Layout.Type.VERTICAL;// 水平布局固定可视区域的宽度contentTransform.width = this._scrollSize.width;contentLayout.spacingX = 0;contentLayout.spacingY = 10;}else if (this._layoutType === kLayoutType.GRID) {// 设置子节点排列方向contentLayout.verticalDirection = Layout.VerticalDirection.TOP_TO_BOTTOM;contentLayout.horizontalDirection = Layout.HorizontalDirection.LEFT_TO_RIGHT;// 设置布局类型contentLayout.type = Layout.Type.GRID;// 设置子节点间隔contentLayout.spacingX = 10;contentLayout.spacingY = 10;// 设置布局约束contentLayout.constraint = Layout.Constraint.FIXED_COL;// 设置布局约束的限定值contentLayout.constraintNum = 5;// 格子固定可视区域的宽度contentTransform.width = this._scrollSize.width;// 设置子节点数量itemCount = 30;}// 填充scrollcontent.removeAllChildren();for (let i = 0; i < itemCount; ++i) {let itemNode = instantiate(this.itemPrefab);this.refreshItem(i, itemNode);itemNode.parent = content;}// 更新布局contentLayout.updateLayout();}// 更新itemprivate refreshItem(index: number, itemNode: Node) {// 不同的布局item的大小会进行改变,用于演示const transform = itemNode.getComponent(UITransform);if (this._layoutType === kLayoutType.VERTICAL) {transform.setContentSize(60, this._scrollSize.height);}else if (this._layoutType === kLayoutType.HORIZONTAL) {transform.setContentSize(this._scrollSize.width, 60);}else if (this._layoutType === kLayoutType.GRID) {transform.setContentSize(70, 70);}// titleconst label = itemNode.getChildByName("title").getComponent(Label);label.string = index.toString();}
}

这个示例一般不会发生在实际的项目开发中,但对于理解ScrollView代码很有帮助!


回调事件


ScrollView滚动视图的事件回调函数主要在scrollEvents中,它的事件类型主要有:

export enum cocos_ui_scroll_view_EventType {// 滚动视图滚动到顶部边界事件SCROLL_TO_TOP = "scroll-to-top",// 滚动视图滚动到底部边界事件SCROLL_TO_BOTTOM = "scroll-to-bottom",// 滚动视图滚动到左边界事件SCROLL_TO_LEFT = "scroll-to-left",// 滚动视图滚动到右边界事件SCROLL_TO_RIGHT = "scroll-to-right",// 滚动视图滚动开始时发出的事件SCROLL_BEGAN = "scroll-began",// 滚动视图滚动结束的时候发出的事件SCROLL_ENDED = "scroll-ended",// 滚动视图滚动到顶部边界并且开始回弹时发出的事件BOUNCE_TOP = "bounce-top",// 滚动视图滚动到底部边界并且开始回弹时发出的事件BOUNCE_BOTTOM = "bounce-bottom",// 滚动视图滚动到左边界并且开始回弹时发出的事件BOUNCE_LEFT = "bounce-left",// 滚动视图滚动到右边界并且开始回弹时发出的事件BOUNCE_RIGHT = "bounce-right",// 滚动视图正在滚动时发出的事件SCROLLING = "scrolling",// 滚动视图自动滚动快要结束的时候发出的事件SCROLL_ENG_WITH_THRESHOLD = "scroll-ended-with-threshold",// 当用户松手的时候会发出一个事件TOUCH_UP = "touch-up"
}

事件的回调主要有三种:

  1. 通过编译器的ScrollEvents设定
  2. 通过脚本代码的scrollview.node.on 设定
  3. 通过脚本代码定义EventHandler对象设定

这里,我们使用第二种方式编写示例:

protected onEnable(): void {this.scroll.node.on(ScrollView.EventType.SCROLLING, this.scrolling, this);
}protected onDisable(): void {this.scroll.node.off(ScrollView.EventType.SCROLLING, this.scrolling, this);
}// 此种方式的回调,参数只会有一个为ScrollView组件
private scrolling(scrollView: ScrollView) {console.log("------ ScrollView 滚动中")}

注意:使用编译器设定ScrollEvents或创建EventHandler对象,支持参数为三个

public scrollEvent(scroll: ScrollView, eventType: any, customData: any) {// 返回三个参数,分别对应ScrollView组件,事件类型,自定义数据
}

视图滚动


在项目的开发中,针对于某些功能我们可能需要将视图滚动到指定的位置。

官方为此提供了一些接口用于这些功能的实现,主要有:

/*
@func: 视图内容将在指定时间滚动到底部、顶部、左侧、右侧、左上、右上、左下、右下
@param: timeInSecond 滚动时间,以秒为单位。如果超时,则立即跳到指定边界
@param: attenuated 滚动速度是否衰减,默认为true
*/
scrollToBottom(timeInSecond?: number, attenuated?: boolean): void;
scrollToTop(timeInSecond?: number, attenuated?: boolean): void;
scrollToLeft(timeInSecond?: number, attenuated?: boolean): void;
scrollToRight(timeInSecond?: number, attenuated?: boolean): void;
scrollToTopLeft(timeInSecond?: number, attenuated?: boolean): void;
scrollToTopRight(timeInSecond?: number, attenuated?: boolean): void;
scrollToBottomLeft(timeInSecond?: number, attenuated?: boolean): void;
scrollToBottomRight(timeInSecond?: number, attenuated?: boolean): void;// 视图滚动到指定的偏移位置
scrollToOffset(offset: math.Vec2, timeInSecond?: number, attenuated?: boolean): void;
// 获取当前滚动偏移量
getScrollOffset(): math.Vec2;
// 获取最大可滚动偏移量
getMaxScrollOffset(): math.Vec2;// 视图是否滚动指定的百分比位置
scrollTo(anchor: math.Vec2, timeInSecond?: number, attenuated?: boolean): void;
scrollToPercentVertical(percent: number, timeInSecond?: number, attenuated?: boolean): void;
scrollToPercentHorizontal(percent: number, timeInSecond: number, attenuated: boolean): void;
// 是否滚动中
isAutoScrolling(): boolean;
// 停止滚动
stopAutoScroll(): void;

简单的示例:

/*
@func: 视图滚动到底部, 如果在滚动中则停止
@param: duration 持续时间,以秒为单位
@param isAttenuate 滚动速度是否衰减
*/
private scrllToBottom(duration: number, isAttenuate:boolean) {// 检测视图是否滚动中if (this.scroll.isAutoScrolling()) {// 如果视图滚动中,则停止滚动this.scroll.stopAutoScroll();return;}this.scroll.scrollToBottom(duration, isAttenuate);
}/*
@func: 视图滚动到指定的索引位置
@param: 目标索引
@notice: 假设可视区域item最大显示三个,如果索引<3则停止滚动
*/
private scrollToIndex(targetIndex: number) {if (targetIndex < 3) {return;}// 获取content大小let contentSize = this.scroll.content.getComponent(UITransform).contentSize;console.log("contentSize:", contentSize.height);// 获取布局垂直间隔let layout = this.scroll.content.getComponent(Layout);let spaceY = layout.spacingY;// 获取item大小let itemNode = this.scroll.content.children[0];let itemSize = itemNode.getComponent(UITransform).contentSize;// 获取滚动偏移量并进行设置const curOffset = this.scroll.getScrollOffset();const offsetY = targetIndex * (itemSize.height + spaceY);this.scroll.scrollToOffset(new Vec3(0, offsetY, 0));
}

最后祝大家学习生活愉快!

这篇关于cocosCreator 之 ScrollView的基本使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/390982

相关文章

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命