您的位置:首页 > 移动开发 > Unity3D

【Unity3D】 UGUI实现ScrollView上下拉刷新

2019-03-08 14:46 127 查看

上下拉刷新在工程中经常用到,但是看到网上的一些例子感觉稍显复杂,这里给出自己写的一个简单例子。继承自ScrollRect

[code]using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ScrollRectRef : ScrollRect {

//高度 往下拉是负数   往上拉是正数
float f = -30f;
//是否刷新
bool isRef = false;
//是否处于拖动
bool isDrag = false;
//显示、隐藏刷新字段
public Callback<bool> callback1;
//如果满足刷新条件 执行的方法
public Callback callback2;

protected override void Awake()
{
base.Awake();
onValueChanged.AddListener(ScrollValueChanged);
}

/// <summary>
/// 当ScrollRect被拖动时
/// </summary>
/// <param name="vector">被拖动的距离与Content的大小比例</param>
void ScrollValueChanged(Vector2 vector)
{
//如果不拖动 当然不执行之下的代码
if (!isDrag)
return;
//这个就是Content
RectTransform rect = GetComponentInChildren<ContentSizeFitter>().GetComponent<RectTransform>();
//如果拖动的距离大于给定的值
if (f > rect.rect.height * vector.y)
{
isRef = true;
callback1?.Invoke(true);
}
else
{
isRef = false;
callback1?.Invoke(false);
}
}

public override void OnBeginDrag(PointerEventData eventData)
{
base.OnBeginDrag(eventData);
isDrag = true;
}

public override void OnEndDrag(PointerEventData eventData)
{
base.OnEndDrag(eventData);
callback1?.Invoke(false);
if (isRef)
callback2?.Invoke();
isRef = false;
isDrag = false;
}

}

给出另外一个测试脚本

[code]using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour {

public Text text;
public GameObject s;

// Use this for initialization
void Start () {
CreateObjs();
GetComponent<ScrollRectRef>().callback1 = (state) => { s.SetActive(state); };
GetComponent<ScrollRectRef>().callback2 = CreateObjs;
}

/// <summary>
/// 创建列表
/// </summary>
void CreateObjs()
{
for (int i = 0; i < 7; i++)
{
Text t = Instantiate(text, text.transform.parent, false);
t.gameObject.SetActive(true);
t.text = (text.transform.parent.childCount - 1).ToString();
}
}

}

第一次上传 ,如有错误 ,请多多指正

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: