Setting UICollectionViewCellSize at Run Time

I have a stack view that contains three UICollectionViewstuned so that each one is equal to vertical space. This stack view is set as the height of half the screen, so it uses more space on large devices. This has been configured in Interface Builder.

So, I need to set the cell size UICollectionViewat runtime, since while we are not working, I do not know what the actual cell size will be. I want them to be square, so I just want to take into account the height UICollectionView, subtract the upper and lower sectional inserts and set itemSizeto the resulting size.

I am trying to do this in viewDidLayoutSubviews, since by that time I believe that the initial heights of the collection views are set. However, they seem to be set to 1000x1000 (even if they are much more reasonable sizes in the storyboard), and therefore I calculate the cell size based on the height of the collection view of 1000. This is too large, but I suppose I call again and Get another chance to double-check it. And I do this, but not earlier, UICollectionViewloudly complaining that I’m itemSizewrong (that is, too big to fit in collectionView, which now has the β€œright” size.)

What is the best way to get the behavior I'm looking for without warning from UICollectionView? Setting the size of the collection view item at runtime depending on the possible size UICollectionViewis something that I struggled with in the past, and it never seems the right time to set itemSize. I do not want to dynamically return it, if only because it is not something that changes during the life of the program. There seem to be some inconsistencies arising from the initial presentation of the views.

It seems strange to me that the collection view comes with an initial size of 1000.0 to 1000.0, but I'm not sure how and why to fix it - maybe this is due to the fact that it is built into the stack view?

: UIStackView . , UICollectionView, UIStackView. , viewDidLayoutSubviews, superview. , UIStackView, 1000x1000.

, viewDidLayoutSubviews:

    if collectionView.bounds.size.width > view.bounds.size.width {
        view.layoutIfNeeded()
    }

collectionView UIStackView, view - UIViewController. , , , , , UIStackView .

. , XCode8 XIB , 10001000, . UIStackView s, .

+4
1

sizeForItemAtIndexPath() return itemSize? , UICollectionViewCell .

0

Source: https://habr.com/ru/post/1656287/


All Articles