UGUI中Text的自适应换行问题

方法一:

    Text里的内容已知并且固定,我们可以在Text文本框里编辑时,通过换行键就可以实现。

方法二:

    可以通过代码直接给Text组件的text赋值,效果如下:

代码:

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

public class Test : MonoBehaviour {

    public Text myTest;
	void Start () {
        myTest.text = "<color=red>11111111</color>\n<color=green>666666666</color>";
    }
}

效果:


方法三:

这时你会想,在代码里使用换行符(\n)可以换行,是不是在Text文本框里使用换行符也可以换行啊,事实上是不可以的。为什么会这样呢???原因是Unity会将\n变成\\n,我们只需要将\\n换成\n就可以了。效果如下:

①、仅在Text文本框里使用了换行符(\n)


扫描二维码关注公众号,回复: 1507327 查看本文章

②、在脚本里控制,将\n换成\\n


代码:

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

public class Test : MonoBehaviour {

    public Text myTest;
    public GameObject myText;
	void Start () {
        myTest = myText.GetComponent<Text>();
        myTest.text = myTest.text.Replace("\\n", "\n");
    }
}

方法四:

通过添加组件来实现换行


调整Content Size Fitter的Vertical Fit为Preferred Size(随高度的改变而改变)

设置pivot的Y轴(pivot默认为0.5是从中间向上下同时增加行数,pivot为1只向下增加行数,为0只向上增加行数


猜你喜欢

转载自blog.csdn.net/qq_38721111/article/details/80583605