Resize UICollectionView to Content Size

Summary: I have a child view in the stack view, and this is a child view with program size. It has several empty views to fill the empty space. However, during execution, attempts to resize the child do not work, and he remains the same size as in the storyboard. How to resize a child view so that the stack view evaluates its new size and positions it accordingly.

More: I have a UICollectionView with a custom layout. The layout correctly calculates the position of the subviews (they appear where I want), and return the correct size of the content. The size of the content is narrower than the screen, but possibly longer, depending on the orientation.

A custom layout returns the correct, calculated size, but the collection view does not change.

I tried programmatically resizing the collection view on the parent view of DidLoad. Does not work.

I tried programmatically changing the layout of the collection view in the parent view of DidLoad. Does not work.

I am using Swift 3, Xcode 8.

+4
source share
1 answer

If I understand your question, you need your UICollectionView to have a size equal to its content, in other words, you want your UICollectionView to have an internal size (just like a label that automatically changes based on its text).

UICollectionView, , .

class IntrinsicSizeCollectionView: UICollectionView {
    // MARK: - lifecycle
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)

        self.setup()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if !self.bounds.size.equalTo(self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        get {
            let intrinsicContentSize = self.contentSize
            return intrinsicContentSize
        }
    }

    // MARK: - setup
    func setup() {
        self.isScrollEnabled = false
        self.bounces = false
    }
}

ps: .xib IntrinsicSizeCollectionView ( " " )

+5

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


All Articles