From 4410d4813318d799ca994b8d3fdd922bcfb23bb7 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 1 Nov 2026 14:48:57 +0800 Subject: [PATCH] fix(font): apply requested system font weights --- .../View/Text/Font/CoreTextUtil.swift | 2 +- .../View/Text/Font/FontTests.swift | 56 +++++++++++++++++-- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/Sources/OpenSwiftUICore/View/Text/Font/CoreTextUtil.swift b/Sources/OpenSwiftUICore/View/Text/Font/CoreTextUtil.swift index 5d88a1e50..c0bc77e5f 100644 --- a/Sources/OpenSwiftUICore/View/Text/Font/CoreTextUtil.swift +++ b/Sources/OpenSwiftUICore/View/Text/Font/CoreTextUtil.swift @@ -139,7 +139,7 @@ extension CTFontDescriptor { ) -> CTFontDescriptor { var attributes: [CFString: Any] = [ kCTFontTraitsAttribute: [ - kCTFontWidthTrait: kCTFontWeightRegular, + kCTFontWeightTrait: weight?.value ?? kCTFontWeightRegular, kCTFontUIFontDesignTrait: design, ], kCTFontSizeAttribute: size diff --git a/Tests/OpenSwiftUICoreTests/View/Text/Font/FontTests.swift b/Tests/OpenSwiftUICoreTests/View/Text/Font/FontTests.swift index 74b28e9cc..12ae6f5d8 100644 --- a/Tests/OpenSwiftUICoreTests/View/Text/Font/FontTests.swift +++ b/Tests/OpenSwiftUICoreTests/View/Text/Font/FontTests.swift @@ -2,18 +2,64 @@ // FontTests.swift // OpenSwiftUICoreTests -import Foundation -@_spi(Private) -import OpenSwiftUICore -import Testing - #if canImport(CoreText) import CoreText import Numerics #endif +import Foundation +@_spi(Private) +import OpenSwiftUICore +import Testing struct FontTests { #if canImport(CoreText) + @Test(arguments: [ + (nil, 0.0), + (.ultraLight, -0.8), + (.thin, -0.6), + (.light, -0.4), + (.regular, 0.0), + (.medium, 0.23), + (.semibold, 0.3), + (.bold, 0.4), + (.heavy, 0.56), + (.black, 0.62), + ] as [(Font.Weight?, CGFloat)]) + func systemFontWeight(weight: Font.Weight?, expected: CGFloat) { + let descriptor = Font.system( + size: 32, + weight: weight + ).resolve(in: .large) + let resolvedWeight = CTFontDescriptorGetWeight(descriptor) + + #expect( + resolvedWeight.isApproximatelyEqual( + to: expected, + absoluteTolerance: 0.01 + ) + ) + } + + @Test(arguments: [ + (32.0, Font.Weight.bold, 0.4), + (17.0, Font.Weight.medium, 0.23), + ] as [(CGFloat, Font.Weight, CGFloat)], [ + nil, .default, .serif, .rounded, .monospaced, + ] as [Font.Design?]) + func systemFontPlatformWeight( + request: (size: CGFloat, weight: Font.Weight, expected: CGFloat), + design: Font.Design? + ) { + let font = Font.system( + size: request.size, + weight: request.weight, + design: design + ).platformFont(in: EnvironmentValues()) + + #expect(font.pointSize == request.size) + #expect(font.weight.isApproximatelyEqual(to: request.expected, absoluteTolerance: 0.01)) + } + @Test func fontModifier() { let descriptor = Font.body.resolve(in: .large)