Skip to content

Commit 9408801

Browse files
committed
Improved sizing logic
1 parent f9377f5 commit 9408801

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

Sources/UIKitBackend/UIViewRepresentable.swift

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,10 @@ where Content == Never {
3636
/// - Returns: Information about the view's size. The ``SwiftCrossUI/ViewSize/size``
3737
/// property is what frame the view will actually be rendered with if the current layout
3838
/// pass is not a dry run, while the other properties are used to inform the layout engine
39-
/// how big or small the view can be. Pass `nil` for the maximum width/height if the view
40-
/// has no maximum size (and therefore may occupy the entire screen).
39+
/// how big or small the view can be. The ``SwiftCrossUI/ViewSize/idealSize`` property
40+
/// should not vary with the `proposal`, and should only depend on the view's contents.
41+
/// Pass `nil` for the maximum width/height if the view has no maximum size (and therefore
42+
/// may occupy the entire screen).
4143
///
4244
/// The default implementation uses `uiView.intrinsicContentSize` and `uiView.sizeThatFits(_:)`
4345
/// to determine the return value.
@@ -70,20 +72,27 @@ extension UIViewRepresentable {
7072
let intrinsicSize = uiView.intrinsicContentSize
7173
let sizeThatFits = uiView.sizeThatFits(
7274
CGSize(width: CGFloat(proposal.x), height: CGFloat(proposal.y)))
73-
let roundedSize = SIMD2(
75+
76+
let roundedSizeThatFits = SIMD2(
7477
Int(sizeThatFits.width.rounded(.up)),
7578
Int(sizeThatFits.height.rounded(.up)))
79+
let roundedIntrinsicSize = SIMD2(
80+
Int(intrinsicSize.width.rounded(.awayFromZero)),
81+
Int(intrinsicSize.height.rounded(.awayFromZero)))
82+
7683
return ViewSize(
7784
size: SIMD2(
78-
intrinsicSize.width < 0.0 ? proposal.x : min(proposal.x, roundedSize.x),
79-
intrinsicSize.height < 0.0 ? proposal.y : min(proposal.y, roundedSize.y)
85+
intrinsicSize.width < 0.0 ? proposal.x : roundedSizeThatFits.x,
86+
intrinsicSize.height < 0.0 ? proposal.y : roundedSizeThatFits.y
8087
),
88+
// The 10 here is a somewhat arbitrary constant value so that it's always the same.
89+
// See also `Color` and `Picker`, which use the same constant.
8190
idealSize: SIMD2(
82-
intrinsicSize.width < 0.0 ? proposal.x : roundedSize.x,
83-
intrinsicSize.height < 0.0 ? proposal.y : roundedSize.y
91+
intrinsicSize.width < 0.0 ? 10 : roundedIntrinsicSize.x,
92+
intrinsicSize.height < 0.0 ? 10 : roundedIntrinsicSize.y
8493
),
85-
minimumWidth: max(0, Int(intrinsicSize.width.rounded(.awayFromZero))),
86-
minimumHeight: max(0, Int(intrinsicSize.height.rounded(.awayFromZero))),
94+
minimumWidth: max(0, roundedIntrinsicSize.x),
95+
minimumHeight: max(0, roundedIntrinsicSize.x),
8796
maximumWidth: nil,
8897
maximumHeight: nil
8998
)

0 commit comments

Comments
 (0)