ScroolTest.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using Button = UnityEngine.UI.Button;
  6. using System;
  7. public class ScroolTest : MonoBehaviour
  8. {
  9. public GameObject btnObj;
  10. public Transform parentTrans;
  11. public GameObject scrollViewObj;
  12. private Vector2 scroSize;
  13. public static ScroolTest Instance { get; protected set; }
  14. public event Action<int, string> ButtonBeClickEvent;
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. }
  19. void Awake()
  20. {
  21. if (Instance == null)
  22. Instance = this;
  23. }
  24. // Update is called once per frame
  25. void Update()
  26. {
  27. }
  28. /// <summary>
  29. /// 初始化滑动视图
  30. /// </summary>
  31. /// <param name="nameArr">需要展示的Item的名称数组</param>
  32. /// <param name="scrollViewPostion">滚动视图的位置</param>
  33. /// <param name="scrollViewSize">滚动视图的大小</param>
  34. /// <param name="contentSize">Item的大小</param>
  35. public void InitScrollview(string[] nameArr, Vector3 scrollViewPostion, Vector2 scrollViewSize, Vector2 contentSize)
  36. {
  37. //获取Scrollview并设置视图大小
  38. scrollViewObj.GetComponent<RectTransform>().sizeDelta = scrollViewSize;
  39. scrollViewObj.GetComponent<RectTransform>().position = scrollViewPostion;
  40. GameObject content = GameObject.Find("Content");
  41. content.GetComponent<GridLayoutGroup>().cellSize = contentSize;
  42. //content.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);//重要的是这一句
  43. for (int i = 0; i < nameArr.Length; i++)
  44. {
  45. CreatItem(i, nameArr[i]);
  46. }
  47. }
  48. public void CreatItem(int idx, string name)
  49. {
  50. GameObject obj = Instantiate(btnObj, parentTrans);
  51. Button oneBtn = obj.GetComponentInChildren<Button>();
  52. Text btnText = obj.transform.GetChild(0).GetComponent<Text>();
  53. btnText.text = name;
  54. // btnText.fontSize = 44;
  55. oneBtn.onClick.AddListener(() =>
  56. {
  57. //Debug.Log("按钮" + idx + "被点击了");
  58. ButtonBeClick(idx, name);
  59. });
  60. }
  61. //按钮被点击
  62. public void ButtonBeClick(int index, string btnName)
  63. {
  64. var evt = ButtonBeClickEvent;
  65. if (evt != null) evt(index, btnName);
  66. }
  67. }