yyl
2025-08-11 b2d7bb59dc37c7b350786b076ee2f344b7c8911f
Main/Component/UI/Common/LayoutElementSizeClamp.cs
@@ -1,9 +1,8 @@
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
//控制目标的最大最小尺寸
[ExecuteAlways]
public class LayoutElementSizeClamp : LayoutElement
{
@@ -15,21 +14,34 @@
    [SerializeField] RectTransform m_Target;
    Vector2 targetSizeRef = Vector2.zero;
    private void LateUpdate()
    protected override void OnEnable()
    {
        base.OnEnable();
        if (clampEnable && m_Target != null)
        {
            if (targetSizeRef != m_Target.sizeDelta)
            {
                preferredHeight = Mathf.Clamp(m_Target.rect.height, m_Clamp.minY, m_Clamp.maxY);
                preferredWidth = Mathf.Clamp(m_Target.rect.width, m_Clamp.minX, m_Clamp.maxX);
                targetSizeRef = new Vector2(preferredWidth, preferredHeight);
            }
            UpdateRect().Forget();
        }
    }
    async UniTask UpdateRect()
    {
        await UniTask.DelayFrame(1);
        preferredHeight = -1;
        preferredWidth = -1;
        //频繁调用ForceRebuildLayoutImmediate的原因是
        // 如Text要自适应宽高又要限制宽高, 先要处理宽度刷新后才能计算换行
        // 强制重新计算布局
        LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent as RectTransform);
        preferredWidth = Mathf.Clamp(m_Target.rect.width, m_Clamp.minX, m_Clamp.maxX);
        // 强制重新计算布局
        LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent as RectTransform);
        preferredHeight = Mathf.Clamp(m_Target.rect.height, m_Clamp.minY, m_Clamp.maxY);
    }
    [System.Serializable]
    public struct Clamp
    {