环境:unity 2018.4.12f1 mac
原理:image+text+Layout Group+ContentSizeFitter,根据text的文字的多少去改变背景大小,实现展开收起的效果。
新建一个Scrollview,删除scrollbar(根据需求保留与否)。(scrollbar删除运行会对Viewport大小改变,需要自己去重新设置大小。)
Content 添加Vertical Layout Group(勾选ChildControlSize)和ContentSizeFitter(Vertical Fit 选择 preferered Size),ScrollRect 的Horizontal取消勾选。
接下来制作cell。
第一种:img-text-btn结构。
对参数进行设置:
首先是Image:
添加Vertical Layout Group(勾选ChildControlSize和ChildForceExpand)和ContentSizeFitter(Vertical Fit 选择 preferered Size);pivot中心点设置为(0.5,1)(重要)
通过调节Vertical Layout Group的Padding参数来对其image图片和Button图片一样大
Text:无特殊设置
Button:锚点对其左上角。
接下来是代码。
动态创建cell:
private void Init()
{
var info = textAsset.text.Split(',');
if (cellPrefabs)
{
for (int i = 0; i < 6; i++)
{
string data ="\n\n"+info[i];
UIManager.Instance.CreateUI(cellPrefabs,content, data);
}
}
else
{
Debug.Log("ERROR DATA~~cellPrefabs is null");
}
}
点击时的处理:
private void Onclick()
{
string curryText = transform.GetChild(0).GetComponent<Text>().text;
string changeText = curryText == "" ? data : "";
transform.GetChild(0).GetComponent<Text>().text = changeText;
//强制刷新UI
for (int i = 0; i < transform.parent.childCount; i++)
{
LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent.GetChild(i).GetComponent<RectTransform>());
}
}
完成:
项目在最上面。