最终效果,APP搜索页面的历史记录,横排超过边界,换行。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*create by keefor on 2022/4/6*/
public class KHistoryList : MonoBehaviour
{
private RectTransform content;
private GameObject item;
private List<GameObject> list = new List<GameObject>();
private Action<int,GameObject> render;
private Action<GameObject> clickitem;
public float padding = 20;
// Start is called before the first frame update
void Awake()
{
content = transform as RectTransform;
item = transform.GetChild(0).gameObject;
}
public void SetRenderItem(Action<int,GameObject> render)
{
this.render = render;
}
public void SetOnClickItem(Action<GameObject> click)
{
this.clickitem = click;
}
public void SetNum(int value)
{
HideAll();
var x = padding;
var y = -padding;
var h = padding;
var w = padding;
for (int i = 0; i < value; i++)
{
var ii = GetItem();
var rect = (RectTransform) ii.transform;
render?.Invoke(i,ii);
h = rect.sizeDelta.y > h ? rect.sizeDelta.y : h;
w += rect.sizeDelta.x+padding;
if (w > content.sizeDelta.x)
{
x = padding;
w = rect.sizeDelta.x+2*padding;
y -= (h+padding);
h =rect.sizeDelta.y;
if (-y + h > content.sizeDelta.y-padding){ii.SetActive(false); break;}
}
Debug.Log(x+":"+y);
rect.anchoredPosition3D = new Vector3(x, y);
x = w;
}
}
void HideAll()
{
for (int i = 0; i < list.Count; i++)
{
list[i].SetActive(false);
}
}
GameObject GetItem()
{
for (int i = 0; i < list.Count; i++)
{
if (!list[i].activeSelf)
{
list[i].SetActive(true);
return list[i];
}
}
var ii = Instantiate(item, content);
ii.SetActive(true);
list.Add(ii);
return ii;
}
}
模板需要这么设置
using System.Collections;
using System.Collections.Generic;
using System.Net.Mime;
using UnityEngine;
using UnityEngine.UI;
/*create by keefor on 2022/4/6*/
public class testhistory : MonoBehaviour
{
public KHistoryList history;
private string[] list = new[] {"春江潮水连海平","礼拜","海上明月共潮生","杜月笙","海内存知己","天涯若比邻","你是一头大象","是的"};
// Start is called before the first frame update
void Start()
{
history.SetRenderItem(RenderItem);
history.SetNum(list.Length);
}
private void RenderItem(int arg1, GameObject arg2)
{
var item = arg2.GetComponentInChildren<Text>();
Debug.Log(list[arg1]);
item.text = list[arg1];
var rect = item.transform as RectTransform;
rect.sizeDelta = new Vector2(CalculateLengthOfText(item.text, item), rect.sizeDelta.y);
var rect2 = arg2.transform as RectTransform;
rect2.sizeDelta = new Vector2(rect.sizeDelta.x + 40, rect.sizeDelta.y + 30);
}
int CalculateLengthOfText(string message,Text tex)
{
int totalLength = 0;
Font myFont = tex.font; //chatText is my Text component
myFont.RequestCharactersInTexture(message, tex.fontSize, tex.fontStyle);
CharacterInfo characterInfo = new CharacterInfo();
char[] arr = message.ToCharArray();
foreach (char c in arr)
{
myFont.GetCharacterInfo(c, out characterInfo, tex.fontSize);
totalLength += characterInfo.advance;
}
return totalLength;
}
}