Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constrain label measurements to the provided size constraint #449

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion BlueprintUICommonControls/Sources/AttributedLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,16 @@ public struct AttributedLabel: Element, Hashable {

return ElementContent { constraint, environment -> CGSize in
let label = Self.prototypeLabel
let constraint = constraint.maximum

label.update(model: self, text: text, environment: environment, isMeasuring: true)
return label.sizeThatFits(constraint.maximum)

let size = label.sizeThatFits(constraint)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it work to use textRect(forBounds:limitedToNumberOfLines:) instead?

            return label.textRect(
                forBounds: .init(
                    origin: .zero,
                    size: constraint.maximum
                ),
                limitedToNumberOfLines: numberOfLines
            ).size

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So in general, we spent a LOT of time (in particular, @watt did) in early blueprint days testing the various ways to measure text properly, and sizeThatFits is really the only way to actually reproduce what UILabel does in all cases.


return CGSize(
width: min(constraint.width, size.width),
height: min(constraint.height, size.height)
)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ class AttributedLabelTests: XCTestCase {

test(
in: CGSize(width: 30, height: 20),
expectedSize: CGSize(width: 30, height: 235.5)
expectedSize: CGSize(width: 30, height: 20.0)
)
test(
in: CGSize(width: 100, height: 300),
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- `AttributedLabel` and `Label` will now restrict their measured size to the provided measurement constraint.

### Deprecated

### Security
Expand Down