Skip to content

Commit

Permalink
feat: AttributedString initializer based on SwiftUI Font.
Browse files Browse the repository at this point in the history
  • Loading branch information
laosb committed Feb 23, 2024
1 parent 6eeb716 commit 9053844
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Sources/EasyRichText/ERTFontUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
//

import Foundation
#if canImport(SwiftUI)
import SwiftUI
#endif
#if canImport(AppKit)
import AppKit
#elseif canImport(UIKit)
Expand Down Expand Up @@ -52,4 +55,30 @@ public struct ERTFontUtils {
return self.font(font, with: traits)
}
#endif

#if canImport(SwiftUI)
#if canImport(UIKit)
public func uiFont(from font: Font) -> UIFont? {
var attributedString = AttributedString()
attributedString.swiftUI.font = font
let nsAttributedString = NSAttributedString(attributedString)
let font = nsAttributedString.attribute(.font, at: 0, effectiveRange: nil) as? UIFont
return font
}
public func ctFont(from font: Font) -> CTFont? {
uiFont(from: font) as CTFont?
}
#elseif canImport(AppKit)
public func nsFont(from font: Font) -> NSFont? {
var attributedString = AttributedString()
attributedString.swiftUI.font = font
let nsAttributedString = NSAttributedString(attributedString)
let font = nsAttributedString.attribute(.font, at: 0, effectiveRange: nil) as? NSFont
return font
}
public func ctFont(from font: Font) -> CTFont? {
nsFont(from: font) as CTFont?
}
#endif
#endif
}
13 changes: 13 additions & 0 deletions Sources/EasyRichText/Models/ERTRichText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ public extension ERTRichText {
self.segments = [.init(text: string)]
}

func attributedString(defaultFont: CTFont) -> AttributedString {
segments.map { $0.attributedString(defaultFont: defaultFont) }.reduce(AttributedString(), +)
}
func attributedString(defaultFont: Font) -> AttributedString {
let ctFont = ERTFontUtils.default.ctFont(from: defaultFont)
#if canImport(AppKit)
let fallbackFont = NSFont.preferredFont(forTextStyle: .body)
#elseif canImport(UIKit)
let fallbackFont = UIFont.preferredFont(forTextStyle: .body)
#endif
return attributedString(defaultFont: ctFont ?? fallbackFont)
}

func nsAttributedString(defaultFont: CTFont) -> NSAttributedString {
ERTAttributedStringBridge.default.nsAttributedString(for: attributedString(defaultFont: defaultFont))
}
Expand Down

0 comments on commit 9053844

Please sign in to comment.