需求:右边为ScrollView 可滑动 左边为TabGroup 滑动对应tab变化
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
namespace Babybus.BabyModule
{
public class ScrollManager : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
ScrollRect scrollRect;
public float smoothing = 4;
private bool isDrag = false;
private float targetVertivalPosition = 0;
private float[] pageArray = new float[] { 0.006718779f, 0.35f, 0.68f, 1 }; //设定每一页 设定每一页的float x 信息
public Toggle[] toggleArray;
bool dragOnce = false;
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
dragOnce = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
float posX = scrollRect.verticalNormalizedPosition;
print(posX);
int index = 3;
float offset = Mathf.Abs(pageArray[index] - posX);//默认离第一页最近
for (int i = 0; i < pageArray.Length; i++)
{
float offsettemp = Mathf.Abs(pageArray[i] - posX);
if (offsettemp < offset)
{//绝对值值越小离越近
index = i;
offset = offsettemp;
}
}
targetVertivalPosition = pageArray[index];
toggleArray[index].isOn = true;
}
// Use this for initialization
void Start()
{
scrollRect = this.transform.GetComponent<ScrollRect>();
scrollRect.verticalNormalizedPosition =1;
}
// Update is called once per frame
void Update()
{
if (isDrag == false&&dragOnce)
{
scrollRect.verticalNormalizedPosition = Mathf.Lerp(scrollRect.verticalNormalizedPosition,
targetVertivalPosition, Time.deltaTime * smoothing);//通过插值实现缓慢滚动
}
}
//Tab 点击
public void OnTogglePage_1_Change(bool isOn)
{
if (isOn)
{
targetVertivalPosition = pageArray[3];
dragOnce = true;
}
}
public void OnTogglePage_2_Change(bool isOn)
{
if (isOn)
{
targetVertivalPosition = pageArray[2];
dragOnce = true;
}
}
public void OnTogglePage_3_Change(bool isOn)
{
if (isOn)
{
targetVertivalPosition = pageArray[1];
dragOnce = true;
}
}
public void OnTogglePage_4__Change(bool isOn)
{
if (isOn)
{
targetVertivalPosition = pageArray[0];
dragOnce = true;
}
}
}
}
网友评论