【unity】ScrollView默认显示某个item

如下图,默认 显示 指定的item。

【unity】ScrollView默认显示某个item_第1张图片

方法如下

public static void CenterOn(Transform target, UIScrollView scrollview, int offsetx = 0, int offsety = 0)
	{
		if (target != null && scrollview != null && scrollview.panel != null)
		{
			Vector3[] corners = scrollview.panel.worldCorners;
			Vector3 panelCenter = (corners[2] + corners[0]) * 0.5f;

			Transform panelTrans = scrollview.panel.cachedTransform;

			// Figure out the difference between the chosen child and the panel's center in local coordinates
			Vector3 cp = panelTrans.InverseTransformPoint(target.position);
			Vector3 cc = panelTrans.InverseTransformPoint(panelCenter);
			Vector3 localOffset = cp - cc + new Vector3(offsetx, offsety);

			// Offset shouldn't occur if blocked
			if (!scrollview.canMoveHorizontally) localOffset.x = 0f;
			if (!scrollview.canMoveVertically) localOffset.y = 0f;
			localOffset.z = 0f;

			panelTrans.localPosition = panelTrans.localPosition - localOffset;

			Vector4 co = scrollview.panel.clipOffset;
			co.x += localOffset.x;
			co.y += localOffset.y;
			scrollview.panel.clipOffset = co;
		}
	}

调用

创建item之后,

UITools.CenterOn(_Items[index].transform, _UIScrollView);

 

你可能感兴趣的:(Unity3D)