1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using Button = UnityEngine.UI.Button;
- using System;
- public class ScroolTest : MonoBehaviour
- {
- public GameObject btnObj;
- public Transform parentTrans;
- public GameObject scrollViewObj;
- private Vector2 scroSize;
- public static ScroolTest Instance { get; protected set; }
- public event Action<int, string> ButtonBeClickEvent;
- // Start is called before the first frame update
- void Start()
- {
- }
- void Awake()
- {
- if (Instance == null)
- Instance = this;
- }
- // Update is called once per frame
- void Update()
- {
- }
- /// <summary>
- /// 初始化滑动视图
- /// </summary>
- /// <param name="nameArr">需要展示的Item的名称数组</param>
- /// <param name="scrollViewPostion">滚动视图的位置</param>
- /// <param name="scrollViewSize">滚动视图的大小</param>
- /// <param name="contentSize">Item的大小</param>
- public void InitScrollview(string[] nameArr, Vector3 scrollViewPostion, Vector2 scrollViewSize, Vector2 contentSize)
- {
- //获取Scrollview并设置视图大小
- scrollViewObj.GetComponent<RectTransform>().sizeDelta = scrollViewSize;
- scrollViewObj.GetComponent<RectTransform>().position = scrollViewPostion;
- GameObject content = GameObject.Find("Content");
- content.GetComponent<GridLayoutGroup>().cellSize = contentSize;
- //content.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);//重要的是这一句
- for (int i = 0; i < nameArr.Length; i++)
- {
- CreatItem(i, nameArr[i]);
- }
- }
-
- public void CreatItem(int idx, string name)
- {
- GameObject obj = Instantiate(btnObj, parentTrans);
- Button oneBtn = obj.GetComponentInChildren<Button>();
- Text btnText = obj.transform.GetChild(0).GetComponent<Text>();
- btnText.text = name;
- // btnText.fontSize = 44;
- oneBtn.onClick.AddListener(() =>
- {
- //Debug.Log("按钮" + idx + "被点击了");
- ButtonBeClick(idx, name);
- });
- }
- //按钮被点击
- public void ButtonBeClick(int index, string btnName)
- {
- var evt = ButtonBeClickEvent;
- if (evt != null) evt(index, btnName);
- }
- }
|