Skip to content

Commit

Permalink
Add an extension for String to calculate its width using specific Swi…
Browse files Browse the repository at this point in the history
…ftUI Font
  • Loading branch information
livid committed Dec 7, 2023
1 parent 78cff81 commit 7c85068
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
31 changes: 31 additions & 0 deletions Planet/Helper/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,37 @@ extension String {

return trimmedTag
}

func width(usingFont font: Font) -> CGFloat {
let nsFont: NSFont

// Map SwiftUI Font to NSFont
switch font {
case .largeTitle:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 1.5, weight: .regular)
case .title:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 1.4, weight: .regular)
case .headline:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 1.2, weight: .semibold)
case .subheadline:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 1.1, weight: .regular)
case .body:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize, weight: .regular)
case .callout:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 1.1, weight: .regular)
case .footnote:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 0.9, weight: .regular)
case .caption:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize * 0.8, weight: .regular)
// Add other cases as needed
default:
nsFont = NSFont.systemFont(ofSize: NSFont.systemFontSize)
}

let attributes: [NSAttributedString.Key: Any] = [.font: nsFont]
let size = (self as NSString).size(withAttributes: attributes)
return size.width
}
}

// User Notification
Expand Down
7 changes: 4 additions & 3 deletions Planet/Views/My/MyArticleItemView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ struct MyArticleItemView: View {
Text(article.title)
.font(.headline)
.foregroundColor(.primary)
.lineLimit(1)

Spacer()

Expand All @@ -28,14 +29,14 @@ struct MyArticleItemView: View {
if let summary = article.summary, summary.count > 0 {
Text(summary.prefix(280))
.foregroundColor(.secondary)
if summary.count < 40 {
if String(summary.prefix(280)).width(usingFont: .body) < 160 {
Spacer()
}
}
else if article.content.count > 0 {
Text(article.content.prefix(280))
.foregroundColor(.secondary)
if article.content.count < 40 {
if String(article.content.prefix(280)).width(usingFont: .body) < 160 {
Spacer()
}
}
Expand Down Expand Up @@ -107,7 +108,7 @@ struct MyArticleItemView: View {
} else {
if let siteName = article.originalSiteName {
Section {
Text("Aggregated from " + siteName)
Text("Aggregated from " + siteName)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Planet/versioning.xcconfig
Original file line number Diff line number Diff line change
@@ -1 +1 @@
CURRENT_PROJECT_VERSION = 1819
CURRENT_PROJECT_VERSION = 1820

0 comments on commit 7c85068

Please sign in to comment.