【准备工作】
相关基础知识与注意事项烦请参见拙作——事件接口(零)总述
【接口介绍】
IPointerDownHandler
该接口实现方法如下:
public void OnPointerDown(PointerEventData eventData)
{
//鼠标点击A对象,按下鼠标时A对象响应此事件
}
IPointerUpHandler
该接口实现方法如下:
public void OnPointerUp(PointerEventData eventData)
{
//鼠标点击A对象,抬起鼠标时响应
//无论鼠标在何处抬起(即不在A对象中)
//都会在A对象中响应此事件
//注:响应此事件的前提是A对象必须响应过OnPointerDown事件
Debug.Log("OnPointerUp " + name);
}
IPointerClickHandler
该接口实现方法如下:
public void OnPointerClick(PointerEventData eventData)
{
//鼠标点击A对象,抬起鼠标时A对象响应此事件
//注:按下和抬起时鼠标要处于同一对象上
}
【应用案例】
案例说明
利用本篇介绍的三个接口事件,实现用两个按钮来代替 ScrollBar 从而控制 ScrollView内容的滑动。
具体实施
(1) 创建一个 Scroll View;
(2) 创建两个 Button,分别命名为 ToUpBtn 和 ToDownBtn,表示上滑和下滑;
(3) 为了使效果更加明显,将 Scroll View 的 Content 子对象纵向加长,并添加一些 Text 作为内容;
(4) 搭建后的界面效果如下图所示:
(5) 创建 C# 脚本,命名为 ScrollButton,并添加如下代码:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ScrollButton : MonoBehaviour,
IPointerDownHandler,IPointerUpHandler, IPointerClickHandler
{
public enum DirectionType
{
None = 0,
ToUp,
ToDown
}
public DirectionType Direction;
private int dir
{
get
{
switch (Direction)
{
case DirectionType.None:
return 0;
case DirectionType.ToUp:
return 1;
case DirectionType.ToDown:
return -1;
default:
Debug.LogError("The type of direction is none!");
return 0;
}
}
}
public Scrollbar TargetScrollBar;
//Click type - Long
[Range(0f, 1f)] public float Speed;
private float progress = 0f;
//Click type - Once
public float ScrollViewHeight;
public float ContentHeight;
private float progressLength { get { return ContentHeight - ScrollViewHeight; } }
enum ClickType
{
Once,
Long
}
void ChangeBarValueByBtn(ClickType clickType)
{
progress = TargetScrollBar.value;
if (clickType == ClickType.Long)
progress += Speed * dir * Time.deltaTime;
else if (clickType == ClickType.Once)
progress += ScrollViewHeight / progressLength * dir;
progress = Mathf.Clamp01(progress);
TargetScrollBar.value = progress;
}
private bool isDown = false;
public void OnPointerDown(PointerEventData eventData)
{
isDown = true;
}
public void OnPointerUp(PointerEventData eventData)
{
isDown = false;
}
private float lastUpBtnTime = 0f;
[Range(0f, 1f)] public float DelayTime;
public void OnPointerClick(PointerEventData eventData)
{
if (Time.time - lastUpBtnTime <= DelayTime)
{
ChangeBarValueByBtn(ClickType.Once);
}
}
void Update()
{
if (isDown)
{
if (Time.time - lastUpBtnTime > DelayTime)
{
ChangeBarValueByBtn(ClickType.Long);
}
}
else
{
lastUpBtnTime = Time.time;
}
}
}
(6) 将脚本分别指定给 ToUpBtn 和 ToDownBtn:
将其 Speed 和 Delay Time 属性均指定为 0.5;
将其 Scroll View Height 属性均指定为 221(以 Scroll View 的 Height 属性为准);
将其 Content Height 属性均指定为 522(以 Content 的 Height 属性为准);
将其 Target Scroll Bar 属性均指定为 Scroll View 的子对象 Scrollbar Vertical;
将 ToUpBtn 的 Direction 属性设为 ToUp;
将 ToDownBtn的 Direction 属性设为 ToDown。
(7) 最终效果如下图所示: