UGUI源码分析-拓展ScrollRect自动可否拖动

1.本文内容概述

拓展ScrollRect组件相关内容,当ScrollRect的Conenct没有超过ScrollRect的大小不需要拖动;否则,可拖动。

2.代码分析

代码需要比较 ScrollRect的sizeDelta和Content的sizeDelta进行比较。当Content的宽度(高度)大于Content的宽度(高度)时,则需要拖动;反之亦反。
监听UIBehaviour.OnRectTransformDimensionsChange事件,当Context发生改变需要重置。

3.代码展示

UIScrollDragAdapter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Rainbow.UI
{
/// <summary>
/// 根据Context的bounds,自动判断ScrollRect 是否可以滑动!当检测的几何框大小发生变化的时候会重新计算
/// 以Vertical为例当高度小于ScrollRect的高度,锁定垂直方向上的滑动
/// *要点1、必须挂在需要检测RectTransform变化的GameObject上 Content上
/// *要点2、设置 scrollRect
/// *要点3、设置 dragDir
/// </summary>
[RequireComponent(typeof(RectTransform))]
public class UIScrollDragAdapter : UIBehaviour
{
public ScrollRect scrollRect;
public DragDir dragDir;
RectTransform rectTransform;
RectTransform scrollRectTransform;

public enum DragDir
{
Vertical,
Horizontal,
}

protected override void Start()
{
rectTransform = GetComponent<RectTransform>();
if (scrollRect != null)
{
scrollRectTransform = scrollRect.GetComponent<RectTransform>();
}
OnRectTransformDimensionsChange();
}
protected override void OnRectTransformDimensionsChange()
{
if (rectTransform == null || scrollRectTransform == null)
{
return;
}
Bounds bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(scrollRectTransform, rectTransform);

if (dragDir == DragDir.Vertical)
{
bool dragv = bounds.size.y > scrollRectTransform.sizeDelta.y;
scrollRect.vertical = dragv;
}

if (dragDir == DragDir.Horizontal)
{
bool dragh = bounds.size.x > scrollRectTransform.sizeDelta.x;
scrollRect.horizontal = dragh;
}
}

}
}

4.效果演示