UGUI - 关于ScrollContent 和 Grid使用

效果图:左上区域为准,通过点击+-item添加内容(红色的item)。

UGUI - 关于ScrollContent 和 Grid使用_第1张图片

步骤:

1.新建Canvas,将canvas的rendermode设置成screenspace - camera,canvas scaler中的screen match mode设置为expand(可以不设置);

2.建立一个panel,添加ScrollRect组件,设置是横向还是纵向的滑动效果,以及移动类型movementtype(具体效果可以自行设置试试);

3.在已有的panel下建一个grid,并给与一个verticallayoutgroup或者horizontallayoutgroup(取决于是横向或者纵向的滑动效果,至于与gridlayoutgroup的差别下面会解释下),设置verticallayoutgroup的内容,padding是指item与scrollrect的边缘的距离,spacing指item之间的间隙,childalignmetn指item的对齐方式,childforceexpand 指显示width或者height上的扩展;

4.建立一个item,添加组件layoutelement来控制当前这个item的布局,定义item的最小值和首选大小,或者可以重写最小值或首选大小,这里显示了首选高度为50,将此item作为预设即可。

5.写脚本:将脚本挂在menu上,additem和deleteitem分别是addbutton和deletebutton调用的方法。

  public GameObject _item;
    private int _itemIndex = 0;
    private float _itemChangeHeight = 0;
    private float maxScrollContent = 0;
    public Transform _grid_one;
    public Transform _grid_two;

    void Start()
    {

    }


    public void AddItems()
    {
        GameObject item = GameObject.Instantiate(_item);
        item.GetComponentInChildren().text = "item" + _itemIndex;
        _itemIndex++;
        item.transform.parent = _grid_one;
        item.transform.localPosition = Vector3.zero;
        item.transform.localScale = Vector3.one;
        _itemChangeHeight = item.GetComponent().preferredHeight + _grid_one.GetComponent().spacing;
        ChangeGridOne(_itemChangeHeight);
    }

    public void DeleteItems()
    {
        int count =_grid_one.childCount;
        if ( count > 0)
        {
            _itemChangeHeight = _grid_one.GetChild(count - 1).GetComponent().preferredHeight + _grid_one.GetComponent().spacing;
            ChangeGridOne(-_itemChangeHeight);
            _itemIndex--;
            DestroyObject(_grid_one.GetChild(count - 1).gameObject);
        }
    }

    void ChangeGridOne(float _changeHeight)
    {
        float height = _changeHeight +(_grid_one as RectTransform).rect.height;
        print(height);        
        (_grid_one as RectTransform).sizeDelta = new Vector2((_grid_one as RectTransform).rect.width, height);
        //保证显示最下面的item
        maxScrollContent = (_grid_one.parent as RectTransform).rect.height;
        if (height > maxScrollContent)
        {
            _grid_one.GetComponent().anchoredPosition3D = new Vector3(0, height - maxScrollContent, 0);
        }
    }

注释:

关于gridlayoutgroup和verticallayoutgroup的区别在于:gridlayoutgroup多了个限制item大小的选项,可以进行自动横纵向排布。


你可能感兴趣的:(Unity3D)