Unity 双生ScrollView滑动冲突问题

上一篇解决了循环左右翻页的问题,如果子节点中也存在ScrollView的话,翻到该子节点时左右滑动就不生效了,得解决它们的冲突。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ChildScrollView : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    /// <summary>
    /// 外层被拦截需要正常拖动的ScrollRect
    /// </summary>
    public ScrollRect anotherScrollRect;
    private ScrollRect thisScrollRect;

    void Start()
    {
        thisScrollRect = GetComponent<ScrollRect>();
        if (anotherScrollRect == null)
            anotherScrollRect = GetComponentsInParent<ScrollRect>()[1];
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnBeginDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnDrag(eventData);
        float angle = Vector2.Angle(eventData.delta, Vector2.up);
        //判断拖动方向,防止水平与垂直方向同时响应导致的拖动时整个界面都会动
        if (angle > 45f && angle < 135f)
        {
            thisScrollRect.enabled = false;
            anotherScrollRect.enabled = true;
        }
        else
        {
            anotherScrollRect.enabled = false;
            thisScrollRect.enabled = true;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnEndDrag(eventData);
        //拖动结束后调用外层ScrollView的回弹效果
        if (anotherScrollRect.enabled)
            anotherScrollRect.GetComponent<MainScrollView>().ChildScrollEndDrag(eventData);
        anotherScrollRect.enabled = true;
        thisScrollRect.enabled = true;
    }
}

把脚本挂到子节点的ScrollView上就可以了。

转载:https://blog.youkuaiyun.com/qq_35037137/article/details/88537421

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值