0

iOS 16.2. XCode 14.2.
Block below is a simple AttributedString creation and save.
The two AttributedExtensions functions for custom append() and Bold().
The text is saved as an RTF file using NSAttributedString.
I have removed error checking.

var atr = AttributedString()
        
atr.append("Text 18\n", fontSize: 18)
atr.append(AttributedString.Bold("Bold Text 24", fontSize: 24)!)
        
    
if let rtfURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("file.rtf") {
    let nsa = NSAttributedString(atr)
    let data = try! nsa.data(from: NSRange(location: 0, length: nsa.length), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType : NSAttributedString.DocumentType.rtf])
    try data.write(to: url, options: Data.WritingOptions.atomic)
}
extension AttributedString {
    mutating func append(_ s: String, fontName: String = "Helvetica", fontSize: CGFloat = 12, colour: UnvColour = .black) {
#if os(macOS)
        guard let font = NSFontManager.shared.font(withFamily: fontName, size: fontSize) else { return }
#else
        guard let font = UIFont(name: fontName, size: fontSize) else { return }
#endif
        let cont = AttributeContainer([NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : colour] )
        self.append(AttributedString(s, attributes: cont))
    }

static func Bold(_ s: String, colour: UnvColour = .black, fontName: String = "Helvetica", fontSize: CGFloat = 12) -> AttributedString? {
        if s.isEmpty { return AttributedString(s) }
#if os(macOS)
        guard let bold = NSFontManager.shared.font(withFamily: fontName, traits: .boldFontMask, weight: 5, size: fontSize) else { return nil }
#else
        
        guard let bold = UIFont(name: fontName, size: fontSize) else { return nil }
#endif
        let boldCont = AttributeContainer([NSAttributedString.Key.font : bold, NSAttributedString.Key.foregroundColor : colour] )
        var ab = AttributedString(s)
        ab.setAttributes(boldCont)
        return ab
    }
}

When the file is saved and opened with TextEdit, the font sizes are scaled by .76666666666 (recurring). Size 18pt is now 13.8pt and 24pt is now 18.4pt.

The debugger shows the font sizes are 24 and 18 before the save.

This occurs on iPad device and iPhone simulator.

Anyone seen this before?

tridiak
  • 27
  • 3
  • If I remember correctly, there was the same issue with HTML, and there is a mismatch when saving mixing `pt` & `px` sizes, hence the size always be decreasing by the same factor or increasing (depending on the conversion direction) – Larme Dec 28 '22 at 12:24

0 Answers0