Skip to content

Commit 66ce09e

Browse files
authored
[flow layout] support max width (#13)
1 parent 10e68c9 commit 66ce09e

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

Sources/DynamicList/VersatileCell.swift

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,10 @@ open class VersatileCell: UICollectionViewCell {
150150
return self
151151
}
152152

153+
open func customSizeFitting(size: CGSize) -> CGSize? {
154+
return nil
155+
}
156+
153157
open override func preferredLayoutAttributesFitting(
154158
_ layoutAttributes: UICollectionViewLayoutAttributes
155159
) -> UICollectionViewLayoutAttributes {
@@ -169,19 +173,31 @@ open class VersatileCell: UICollectionViewCell {
169173
height: UIView.layoutFittingCompressedSize.height
170174
)
171175

172-
let before = contentHuggingPriority(for: .horizontal)
173-
self.setContentHuggingPriority(.required, for: .horizontal)
174-
defer {
175-
self.setContentHuggingPriority(before, for: .horizontal)
176-
}
176+
let cellSize: CGSize
177177

178-
let size = systemLayoutSizeFitting(
179-
targetSize,
180-
withHorizontalFittingPriority: .fittingSizeLevel,
181-
verticalFittingPriority: .fittingSizeLevel
182-
)
178+
if let customSize = customSizeFitting(size: targetSize) {
179+
cellSize = customSize
180+
} else {
181+
182+
var size = systemLayoutSizeFitting(
183+
targetSize,
184+
withHorizontalFittingPriority: .fittingSizeLevel,
185+
verticalFittingPriority: .fittingSizeLevel
186+
)
187+
188+
if size.width > targetSize.width {
189+
// re-calculate size with max width.
190+
size = systemLayoutSizeFitting(
191+
targetSize,
192+
withHorizontalFittingPriority: .required,
193+
verticalFittingPriority: .fittingSizeLevel
194+
)
195+
}
196+
197+
cellSize = size
198+
}
183199

184-
layoutAttributes.frame.size = size
200+
layoutAttributes.frame.size = cellSize
185201

186202
return layoutAttributes
187203

0 commit comments

Comments
 (0)