Unity dynamically draws table table pagination

Reminder: The source code is attached to the post~ Everyone can learn from each other

Article directory

Table of contents

Article directory

foreword

1. Component structure

1. Table prefab structure

2. Row prefab structure

3. Project structure

2. Function realization

1. Screening operation module

2. Dynamically generate Table

3. Dynamic loading of row information

4. Entities

Summarize



foreword

日常工作中,时常会有动态绘制表格、根据后台数据填充表格内容的需求!使用频率较高,所以整理出组件,方便每次使用!大家共同学习!


1. Component structure

 1. Table prefab structure

2. Row prefab structure

3. Project structure

2. Function realization

1. Screening operation module

         The method in the UserManager script is used for the overall operation, controlling functions such as the overall refresh, delete, batch delete, and basic parameter setting of the list content.

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

public class UserManager : MonoBehaviour
{
    public static UserManager u_m;
    public Button addButton;
    public Button delAllButton;
    public Button homeButton;
    public Button endButton;
    public Button previousButton;
    public Button nextPageButton;
    public Button importButton;
    public Button exportButton;
    public Dropdown role; 
    public InputField keyWord;
    public Dropdown post;
    public Dropdown grade;
    [System.NonSerialized]
    public int itemCount = 15;
    // [System.NonSerialized]
    // public string[] ids ;
    [System.NonSerialized]
    public List<string> userIds = new List<string>();
    //[System.NonSerialized]
    //public List<User> userList = new List<User>();//查询所有用户数据(导出)
    [System.NonSerialized]
    public bool refresh = false;


    //public Button detailButton;
    //public Button delButton;

    private string type = "";
    private string tipType = "";
    private string modifyContent = "";

    private void Awake()
    {
        u_m = this;

    }

    //Start is called before the first frame update
    void Start()
    {

        //role.ClearOptions();
        //List<string> options = new List<string>();
        //options.Add("全部");
        //for (int i = 0; i < DataBase.Instance().roleList.Count; i++)
        //{
        //    options.Add(DataBase.Instance().roleList[i].RoleName);
        //}
        //role.AddOptions(options);
    }

    // Update is called once per frame
    void Update()
    {
        type = "";
        tipType = "";
        modifyContent = "";
    }

   


    public void ShowTips(string type)
    {
        if (userIds.Count > 0)
        {
            if ("Del".Equals(type))
            {
               // UIManager.Instance().OpenTips(Common.deleteTip, Common.userDelete);
               //弹出提示信息
            }
           
        }
        else
        {
            if ("Del".Equals(type))
            {
                //UIManager.Instance().OpenTips(Common.errorResultTip, Common.delErrorResult);
                //弹出提示信息
            }

        }


    }

    public void ShowImportTips()
    {
        //UIManager.Instance().OpenTips(Common.importTip, Common.userImport);
    }

    public void ShowExportTips()
    {
        //UIManager.Instance().OpenTips(Common.exportTip, Common.userExport);
    }

   
    /// <summary>
    /// 批量删除
    /// </summary>
    public void BatchDeleteUsers()
    {
        //int temp = ServiceManager.Instance().DeleteUsers(userIds);
        int status = 1;
        //if (temp == 0)
        if(true)
        {
            status = 0;
            UserManager.u_m.refresh = true;
            //type = Common.successResultTip;
            tipType = "批量删除成功!";
        }
        else
        {
            //type = Common.errorResultTip;
            tipType = "批量删除失败!";
        }
        //增加log
        //LogInfo logInfo = new LogInfo();
        //logInfo.UserName = DataBase.Instance().loginUserInfo.UserName;
        //logInfo.OperationStatus = status.ToString();
        //logInfo.OperationName = Common.userDeleteLog;
        //ServiceManager.Instance().AddLog(logInfo);

    }


    public void EmpowerUsers(string type)
    {
        //    List<User> userList = new List<User>();
        //    for (int i = 0; i < userIds.Count; i ++)
        //    {
        //        User user = ServiceManager.Instance().GetUserInfo(userIds[i]);
        //        user.Type = type;
        //        int temp = ServiceManager.Instance().ModifyUser(user);
        //        if (temp == 0)
        //        {
        //            UserManager.u_m.refresh = true;
        //            Log logInfo = new Log();
        //            logInfo.UserId = DataBase.Instance().loginUserInfo.UserId;
        //            logInfo.Ip = DataBase.Instance().loginUserIp;
        //            if ("0".Equals(type))
        //            {
        //                logInfo.Content = Common.userNoEmpowerLog;
        //            }
        //            else
        //            {
        //                logInfo.Content = Common.userEmpowerLog;
        //            }
        //            ServiceManager.Instance().AddLog(logInfo);
        //            //type = Common.successResultTip;
        //            tipType = "批量授权成功!";
        //        }
        //        else
        //        {

        //            //type = Common.errorResultTip;
        //            tipType = "批量授权失败!";
        //        }
        //    }


        //}

    }

}

2. Dynamically generate Table

  • Fill the form according to the background data (here is used for display, use the default data, and normally access the background interface to obtain real data to fill the form).
   public void SetPage(int index, int homeType = 0)
    {
        if (homeType != 0)
        {
            nowPage = 1;
            //避免重复刷新首页
            if ("1".Equals(CurrentPage.text))
            {
                return;
            }
        }

        //避免重复刷新尾页
        if (index == 10000 && CurrentPage.text.Equals(AllPageCount.text))
        {
            return;
        }

        //避免首页刷上一页,避免尾页刷下一页
        if (index == -1)
        {
            if (int.Parse(CurrentPage.text) - 1 < 1) return;
        }
        if (index == 1)
        {
            if (int.Parse(AllPageCount.text) - int.Parse(CurrentPage.text) < 1) return;
        }


        string role = "";
        string post = "";
        string grade = "";
        if (UserManager.u_m.role.value != 0)
        {
            role = (UserManager.u_m.role.value  - 1).ToString();
        }

        if (UserManager.u_m.post.value != 0)
        {
            post = (UserManager.u_m.post.value - 1).ToString();
        }
        if (UserManager.u_m.grade.value != 0)
        {
            grade = (UserManager.u_m.grade.value - 1).ToString();
        }


        int page = 20;
        //int page = ServiceManager.Instance().GetUserCount(UserManager.u_m.keyWord.text, role, post, grade);

        maxPage = page / UserManager.u_m.itemCount;
        maxPage = page % UserManager.u_m.itemCount != 0 ? maxPage + 1 : maxPage;
        nowPage += index;


        nowPage = nowPage > maxPage ? maxPage : nowPage;
        nowPage = nowPage < 1 ? 1 : nowPage;
        
        CurrentPage.text = nowPage.ToString();
        AllPageCount.text = maxPage.ToString();

        //初始化id组
        //for (int i = 0; i < UserManager.u_m.itemCount; i++)
        //{
        //    UserManager.u_m.ids[i] = "-1";
        //}

        //清空行
        if (content.childCount > 0)
        {
            for (int i = 0; i < content.childCount; i++)
            {
                Destroy(content.GetChild(i).gameObject);
            }
        }

        //清空选中
        UserManager.u_m.userIds.Clear();


        //*************虚拟数据开始*******************
        int rowCount = 15;
        if ("2".Equals(CurrentPage.text))
        {
            rowCount = 5;
        }
        for (int i = 0; i < rowCount; i++)
        {
            GameObject go = Instantiate(Resources.Load("Prefabs/UserRow"), content) as GameObject;
            if (i % 2 != 0)
            {
                for (int j = 0; j < go.transform.GetChild(0).childCount; j++)
                {
                    go.transform.GetChild(0).GetChild(j).GetComponent<Image>().sprite = Resources.Load<Sprite>("UI/样式B-1");
                }
            }
        }
        //*************虚拟数据结束*******************



        //*************实际数据开始*******************
        //List<UserInfo> userList = ServiceManager.Instance().GetUserList(UserManager.u_m.keyWord.text, role, post, grade, CurrentPage.text, UserManager.u_m.itemCount.ToString());

        预制体加载行
        //for (int i = 0; i < userList.Count; i++)
        //{

        //    GameObject go = Instantiate(Resources.Load("Prefabs/UserManager/UserRow"), content) as GameObject;
        //    if (i % 2 != 0)
        //    {
        //        for (int j = 0; j < go.transform.GetChild(0).childCount; j++)
        //        {
        //            go.transform.GetChild(0).GetChild(j).GetComponent<Image>().sprite = Resources.Load<Sprite>("UI/样式B-1");
        //        }
        //    }

        //    go.GetComponent<UserRow>().id = userList[i].UserId.ToString();
        //    go.GetComponent<UserRow>().index.text = ((nowPage - 1) * UserManager.u_m.itemCount + i + 1).ToString();
        //    go.GetComponent<UserRow>().code.text = userList[i].UserNo;
        //    go.GetComponent<UserRow>().company.text = int.Parse(userList[i].DeptId) == 0 ? "技术部一室" : "发测站三室";
        //    go.GetComponent<UserRow>().userName.text = userList[i].UserName;
        //    go.GetComponent<UserRow>().role.text = userList[i].RoleName;
        //    go.GetComponent<UserRow>().grade.text = int.Parse(userList[i].PostId) == 0 ? "技术总体":"岗位操作" ;
        //    switch (int.Parse(userList[i].Grade))
        //    {
        //        case 0:
        //            go.GetComponent<UserRow>().type.text = "岗前";
        //            break;
        //        case 1:
        //            go.GetComponent<UserRow>().type.text = "初级";
        //            break;
        //        case 2:
        //            go.GetComponent<UserRow>().type.text = "中级";
        //            break;
        //        case 3:
        //            go.GetComponent<UserRow>().type.text = "高级";
        //            break;
        //    }
        //    // UserManager.u_m.ids[i] = go.GetComponent<UserRow>().id;
        //}
        //*************实际数据结束*******************
    }

  • Bind the AllChoice method to the toggle component of the row to control the row selection and unselection styles.
 public void AllChoice(bool isOn)
    {
        if (isOn)
        {
            for (int i = 0; i < content.childCount; i++)
            {
                content.GetChild(i).GetChild(0).GetChild(0).GetChild(0).GetComponent<Toggle>().isOn = true;
            }
        }
        else
        {
            for (int i = 0; i < content.childCount; i++)
            {
                content.GetChild(i).GetChild(0).GetChild(0).GetChild(0).GetComponent<Toggle>().isOn = false;
            }
        }
    }

 3. Dynamic loading of row information

Each row is bound to the UserRow script, which is used for dynamic assignment and value retrieval of row information, and the row operation functions to be improved can be realized on this page.

public class UserRow : MonoBehaviour
{
    [System.NonSerialized]
    public string id;
    public Toggle choice;
    public Text index;
    public Text code;
    public Text company;
    public Text userName;
    public Text role;
    public Text grade;
    public Text type;
    //public Button detailB;
    public Button modifyB;

    // Start is called before the first frame update
    void Start()
    {
        //TEST
        //index.text = "1";
        //userName.text = "张靓颖";
        //code.text = "2022060701";
        //role.text = "管理员";
        //company.text = "空军总部";
        //date.text = DateTime.Now.ToString();
    }

    // Update is called once per frame
    void Update()
    {
        if (choice.isOn)
        {
            transform.GetChild(1).gameObject.SetActive(true);
            if (!UserManager.u_m.userIds.Contains(id))
            {    
                UserManager.u_m.userIds.Add(id);
            }
        }
        else
        {
            transform.GetChild(1).gameObject.SetActive(false);
            if (UserManager.u_m.userIds.Contains(id))
            {  
                UserManager.u_m.userIds.Remove(id);
            }
        }
    }

    //public void ShowDetailPanel()
    //{
    //    UIManager.Instance().OpenUserDetailPanel(id);
    //}

    //public void showModifyPanel()
    //{
    //    UIManager.Instance().OpenUserAddPanel(1, id);
    //}
}

4. Entities

The entity class is UserInfo, which is used to interact with the background, store each piece of user information, and be used for dynamic assignment and value retrieval. There is a one-to-one correspondence between fields and page row fields.

Summarize

The component structure is simple, the hierarchy is clear, and it is easy to understand. The ui and size can be changed for different occasions. Personal summary and induction, easy to use. Avoid reinventing the wheel~~~

CSDN component download: https://download.csdn.net/download/u014641682/87621080

Guess you like

Origin blog.csdn.net/u014641682/article/details/129815616