gilzoide / unity-flex-ui

Flexbox layout support for Unity UI using the Yoga layout engine
The Unlicense
98 stars 5 forks source link

Add support for ContentSizeFitter #24

Open asger60 opened 4 months ago

asger60 commented 4 months ago

As the title says, I think it would be very useful if we could have support ContentSizeFitter.

Syjgin commented 3 months ago

+1, can't use this asset for this reason

Syjgin commented 3 months ago

Found a workaround: you can calculate content size programmatically. For example, for vertical layout it will be look like this:

...
        private const float PaddingW = 25f;
        private const float PaddingH = 25f;
        [SerializeField] private RectTransform _content;
        [SerializeField] private RectTransform scrollViewTransform; // to get max scroll content width

...
        public void SetContent(IReadOnlyCollection<TItem> content)
        {
            CleanContent();
            float contentHeight = 0f;
            float maxContentWidth = scrollViewTransform.sizeDelta.x;
            float currentContentWidth = 0f;
            foreach (TItem itemViewModel in content)
            {
                ItemUIView<TItem> itemView = CreateItemView(itemViewModel);

                float widthAddition  = itemView.GetComponent<RectTransform>().sizeDelta.x + PaddingW;
                currentContentWidth += widthAddition;
                float remainWidth = maxContentWidth - currentContentWidth;
                if (remainWidth < widthAddition)
                {
                    contentHeight += itemView.GetComponent<RectTransform>().sizeDelta.y + PaddingH;
                    currentContentWidth = 0f;
                }

            }
            _content.sizeDelta = new Vector2(0f, contentHeight);
        }
...
gilzoide commented 1 month ago

Hey @asger60, thanks for the report. I agree that this should be added, it's super useful for text and image to be laied out according to their content size.

In the Yoga part of things, I think we need to hook measure functions for this to work properly. Also, I think ContentSizeFitter will want to relayout the element after FlexLayout does, so we'd likely have to use ILayoutElement.preferedHeight/preferedWidth for measuring instead of using ContentSizeFitter at all.