-
-
Notifications
You must be signed in to change notification settings - Fork 580
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve wrapping of single-line texts in preview
Better than used to be, though not perfect and very hard to do for such a basic problem with SwiftUI. Fixes #880
- Loading branch information
Showing
3 changed files
with
35 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import SwiftUI | ||
|
||
// A text view that properly wraps single-line content without extra horizontal or vertical spaces. | ||
// https://www.reddit.com/r/SwiftUI/comments/1gx1w6v/how_to_wrap_a_text_inside_a_macos_popover/ | ||
struct WrappingTextView: View { | ||
let text: String | ||
let maxWidth: CGFloat | ||
|
||
private let charHeight: CGFloat = 10 | ||
private let charWidth: CGFloat = 6 | ||
|
||
private var approxWidth: CGFloat { | ||
let width = CGFloat(text.count) * charWidth | ||
return min(max(width, 50), maxWidth) | ||
} | ||
|
||
private var approxHeight: CGFloat { | ||
let width = CGFloat(text.count) * charWidth | ||
return width / min(max(width, 50), maxWidth) * charHeight * 3 | ||
} | ||
|
||
var body: some View { | ||
Text(text) | ||
.frame(idealWidth: approxWidth, maxHeight: approxHeight, alignment: .leading) | ||
.font(.body) | ||
} | ||
} |