1.本文内容概述
拓展ScrollRect组件相关内容,当ScrollRect的Conenct没有超过ScrollRect的大小不需要拖动;否则,可拖动。
2.代码分析
代码需要比较 ScrollRect的sizeDelta和Content的sizeDelta进行比较。当Content的宽度(高度)大于Content的宽度(高度)时,则需要拖动;反之亦反。
监听UIBehaviour.OnRectTransformDimensionsChange事件,当Context发生改变需要重置。
3.代码展示
UIScrollDragAdapter.cs1 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 { [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.效果演示