<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Just Do Swift on Medium]]></title>
        <description><![CDATA[Stories by Just Do Swift on Medium]]></description>
        <link>https://medium.com/@justdoswift?source=rss-3197a4eecb20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rzGnQcIxJGyLiMGOSeivYw.png</url>
            <title>Stories by Just Do Swift on Medium</title>
            <link>https://medium.com/@justdoswift?source=rss-3197a4eecb20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:24:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justdoswift/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Animate Handwriting in SwiftUI]]></title>
            <link>https://medium.com/@justdoswift/how-to-animate-handwriting-in-swiftui-195341c7942a?source=rss-3197a4eecb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/195341c7942a</guid>
            <category><![CDATA[animate]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Just Do Swift]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 11:03:30 GMT</pubDate>
            <atom:updated>2025-06-28T11:03:30.813Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1097133955%3Fh%3D28063b302c%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1097133955%2F28063b302c&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2031379548-030dd3beb10e7aab3033b8c1b9169aac9cb9a9c726ba5b71d2c391cde47bb9c2-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cf08816987698efb2e28b86f273451a/href">https://medium.com/media/9cf08816987698efb2e28b86f273451a/href</a></iframe><p>There’s a fun, unique enjoyment from watching code write itself.</p><p>Using the appropriate method you can cause text to “write” itself to the screen — stroke by stroke, letter by letter.</p><p>This is not just eye-candy (though its wonderfully fun).</p><p>It’s a launching point for onboarding screens, animated UI, and even code editors with custom syntax highlighting.</p><p>We’ll break down a real-world implementation.</p><p>You’ll understand why it works, and once we finish, you’ll be able to implement your own text-to-path animation in SwiftUI.</p><p>No black boxes.</p><p>Every step explained.</p><h3>What is the Problem, Exactly?</h3><p>SwiftUI easily lays out the standard Text views.</p><p>But when you want to animate the writing of text — where each letter, appears as it is written — it cannot do this out of the box.</p><p>You need to do three things:</p><ol><li>Convert your text to vector paths (the lines and curves that stand for each glyph).</li><li>Animate the displaying of those paths.</li><li>Wrap all of this in a reusable and SwiftUI-based shape.</li></ol><p>SwiftUI does not give you any API to breakdown a String to its individual glyphs or get at the vector shapes.</p><p>That is why we will use Core Text because it has CTLineGetGlyphRuns so we know exactly how we want the text broken down into glyph runs, and then we can draw and animate them in a very detailed way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*qTDvQpr-fToCkhQw.png" /></figure><h3>The Heart of It — Converting Text into Paths</h3><p>The real work is in the custom Shape, TextPath.</p><p>In order to animate handwritten text you need to get the vector shapes for each individual glyph.</p><p>SwiftUI cannot do this (yet), but Core Text can handle this.</p><p>This is where Core Text comes in.</p><p>Core Text is a lower level text system that can break apart any string into its raw glyphs and paths.</p><p>Specifically CTLineGetGlyphRuns lets you go through each glyph, retrieve the outline, and draw it accurately.</p><p>Let’s walk through how TextPath works:</p><h4>1. Convert the String to Glyph Runs</h4><p>To start, you convert your string and font to an attributed string, and then create a Core Text line.</p><p>This line has one of more glyph runs:</p><pre>let attrString = NSAttributedString(string: text, attributes: [.font: font])<br>let line = CTLineCreateWithAttributedString(attrString)<br>let runs = CTLineGetGlyphRuns(line) as! [CTRun]</pre><p>Each run is a group of glyphs that have the same attributes.</p><h4>2. Get and Place Each Glyph</h4><p>Loop through the runs, and for each glyph get its position and outline, and add it to the overall path:</p><pre>for run in runs {<br>    let runFont = CTRunGetAttributes(run) as NSDictionary<br>    let font = runFont[kCTFontAttributeName as NSString] as! CTFont<br>    for i in 0..&lt;CTRunGetGlyphCount(run) {<br>        let glyphRange = CFRangeMake(i, 1)<br>        var glyph = CGGlyph()<br>        var position = CGPoint()<br>        CTRunGetGlyphs(run, glyphRange, &amp;glyph)<br>        CTRunGetPositions(run, glyphRange, &amp;position)<br>        if let letter = CTFontCreatePathForGlyph(font, glyph, nil) {<br>            let xform = CGAffineTransform(translationX: position.x, y: position.y)<br>            path.addPath(Path(letter).applying(xform))<br>        }<br>    }<br>}</pre><p><strong>What’s actually happening in that loop?</strong></p><p>Think of it this way: every letter you see on your screen is a glyph, and Core Text organizes those glyphs into groups called “runs” (runs can be distinguished because they share the same font/style etc.). For each run, and every glyph in that run, the code:</p><ul><li>Finds the font for this group of glyphs.</li><li>For each glyph gets the glyph’s index and where it is going to be positioned in the line.</li><li>Uses CTFontCreatePathForGlyph to get the vector outline (the “shape” of the letter).</li><li>Translate that outline to the exact position on the screen (using a translation transform).</li><li>Adds it to the main path that represents the entire word or phrase.</li></ul><p>It’s like laying down the stencils for each letter, putting them in the right spots, and drawing their outlines in the right order to spell out your string. This is how you get from text, to a vector path that can be animated.</p><h4>3. Align and Center the Path</h4><p><strong>Why flip and center the path?</strong></p><p>This part helps address a common pain point that occurs when UIKit and Core Text treats (0,0) as the <strong>top-left</strong> of the screen, while SwiftUI’s Shape system has (0,0) at the <strong>bottom-left</strong>.</p><p>If you draw the Core Text path without telling SwiftUI to adjust where the paths are drawn, everything is drawn upside down.</p><p>So first you flip the Y-axis (think of flipping a transparency over):</p><pre>let scaleTransform = CGAffineTransform(scaleX: 1, y: -1)<br>let flipYPath = path.applying(scaleTransform)</pre><p>But after flipping, your text is now below the viewable area — so you move (translate) the path upwards so it sits within the canvas:</p><pre>let translateYTransform = CGAffineTransform(translationX: 0, y: bounds.height)<br>let finalPath = flipYPath.applying(translateYTransform)</pre><p>Lastly, to <strong>center</strong> the text in the available rectangle (so it doesn’t hug any edge), you measure the path’s bounding box and shift it so it’s perfectly centered both horizontally and vertically.</p><p>Here’s the code:</p><pre>let finalBounds = finalPath.boundingRect<br>let xOffset = (rect.width - finalBounds.width) / 2 - finalBounds.minX<br>let yOffset = (rect.height - finalBounds.height) / 2 - finalBounds.minY<br>return finalPath.applying(CGAffineTransform(translationX: xOffset, y: yOffset))</pre><p>Essentially, the object measures the final path itself, determines the remaining space on either side, and shifts the object to the center position in the drawing area.</p><p>The process is like writing a word on a clear, thin film, inverting it, and then sliding it up and over until it is centered in a picture frame.</p><p>Here is the complete code for reference:</p><pre>struct TextPath: Shape {<br>    var text: String<br>    var font: UIFont<br>    func path(in rect: CGRect) -&gt; Path {<br>        let attrString = NSAttributedString(string: text, attributes: [.font: font])<br>        let line = CTLineCreateWithAttributedString(attrString)<br>        let runs = CTLineGetGlyphRuns(line) as! [CTRun]<br>        var path = Path()<br>        for run in runs {<br>            let runFont = CTRunGetAttributes(run) as NSDictionary<br>            let font = runFont[kCTFontAttributeName as NSString] as! CTFont<br>            for i in 0..&lt;CTRunGetGlyphCount(run) {<br>                let glyphRange = CFRangeMake(i, 1)<br>                var glyph = CGGlyph()<br>                var position = CGPoint()<br>                CTRunGetGlyphs(run, glyphRange, &amp;glyph)<br>                CTRunGetPositions(run, glyphRange, &amp;position)<br>                if let letter = CTFontCreatePathForGlyph(font, glyph, nil) {<br>                    let xform = CGAffineTransform(translationX: position.x, y: position.y)<br>                    path.addPath(Path(letter).applying(xform))<br>                }<br>            }<br>        }<br>        // Flip Y-axis<br>        let scaleTransform = CGAffineTransform(scaleX: 1, y: -1)<br>        let flipYPath = path.applying(scaleTransform)<br>        // Move up so baseline is at bottom<br>        let translateYTransform = CGAffineTransform(translationX: 0, y: path.boundingRect.height)<br>        let finalPath = flipYPath.applying(translateYTransform)<br>        // Center horizontally and vertically<br>        let finalBounds = finalPath.boundingRect<br>        let xOffset = (rect.width - finalBounds.width) / 2 - finalBounds.minX<br>        let yOffset = (rect.height - finalBounds.height) / 2 - finalBounds.minY<br>        return finalPath.applying(CGAffineTransform(translationX: xOffset, y: yOffset))<br>    }<br>}</pre><h3>How It Comes Together: Using TextPath in SwiftUI</h3><p>The HandwritingText view is where you put it to work.</p><p>It wraps TextPath, applies a stroke, and animates the path using .trim(from:to:).</p><p>When you toggle the draw state, the path draws itself as if by hand.</p><pre>struct HandwritingText: View {<br>    @State private var draw: Bool = false<br>    var body: some View {<br>        VStack {<br>            TextPath(text: &quot;Hello SwiftUI!&quot;, font: UIFont.systemFont(ofSize: 50))<br>                .trim(from: 0, to: draw ? 1 : 0)<br>                .stroke(Color.blue, lineWidth: 2)<br>                .frame(height: 60)<br>                .onAppear { draw.toggle() }<br>            Toggle(&quot;Draw&quot;, isOn: $draw).labelsHidden()<br>        }<br>        .animation(.easeInOut(duration: 3.0), value: draw)<br>        .padding()<br>    }<br>}</pre><ul><li>The .trim modifier is what reveals the path as a smooth animation.</li><li>The Toggle lets you replay the handwriting effect.</li></ul><blockquote><strong><em>Note:</em></strong></blockquote><blockquote><em>This approach animates the entire outline of each glyph as a single continuous path.</em></blockquote><blockquote><em>It doesn’t break characters down into their real pen strokes or handwriting orders — so the animation follows the contours of the font, not the way a person would actually write the letter by hand.</em></blockquote><blockquote><em>This is a fundamental limitation of standard fonts: they only store the final shape of each glyph for rendering, not the sequence or direction of strokes used to write it.</em></blockquote><blockquote><em>If you want true stroke-by-stroke animation, you’ll need a specialized dataset (such as stroke-order data for Chinese characters), or you’ll have to create custom stroke paths for each character you wish to animate.</em></blockquote><h3>What You Could Build With This</h3><p>This isn’t even limited to just nifty splash screens.</p><ul><li><strong>Custom Handwriting Effects</strong> (pick any font, even handwriting you imported with SVG).</li><li><strong>Code editors</strong> that highlight the text as it appears to be “typed”.</li><li><strong>Animated diagrams</strong> with text that appears to be being drawn “live”.</li><li><strong>Resizeable, accessible UIs</strong> — everything is a vector path, so at any size/DPI, it scales cleanly.</li></ul><h3>Review: The Building Blocks</h3><p>If you want to try this on your own, here are some points you should remember:</p><ul><li>Core Text is helpful for breaking text into glyphs and paths.</li><li>Be careful with coordinate systems as UIKit and SwiftUI do not match.</li><li>SwiftUI’s .trim and .stroke can help you animate any shape, as long as you can convert your data to a Path.</li></ul><p>This is a pattern you can reproduce well beyond just handwriting effects.</p><p>It is your “open sesame” for any vector text animation in your app.</p><p>And this is how to animate text, one path at a time.</p><p><strong>Interested in more content deep dives like this, with project level code and all the tricks explained?</strong></p><p><strong>Subscribe for your weekly hands-on pattern guides to mastering SwiftUI and mobile AI, without wasted time in “tutorial hell” or on Youtube.</strong></p><p><strong>Article written for the Just Do Swift community. No magic. Just code you can leverage and ship today.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195341c7942a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Better Way to Snapshot SwiftUI Views (Yes, UIKit Is Involved)]]></title>
            <link>https://medium.com/@justdoswift/a-better-way-to-snapshot-swiftui-views-yes-uikit-is-involved-7b2be6f66eba?source=rss-3197a4eecb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2be6f66eba</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[imagerender]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Just Do Swift]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 09:32:53 GMT</pubDate>
            <atom:updated>2025-06-12T09:32:53.828Z</atom:updated>
            <content:encoded><![CDATA[<p>When ImageRenderer isn’t enough, here’s what works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9HU4bGGj4M3hoMyB.png" /></figure><p>Every once in a while, you just need an image.</p><p>You may be building a share sheet.</p><p>You may be recording visual states for debugging.</p><p>You may even want a custom thumbnail.</p><p>Whatever your use case may be, taking a snapshot of a SwiftUI view should be simple.</p><p>Apple did release ImageRenderer in iOS 16 — but if you have used it, you may know it doesn&#39;t always meet your needs.</p><p><strong>That’s why I built this.</strong></p><p>It does still use UIKit, yes. Intentionally. UIKit gives us stable and tested tools to render exactly what is on the screen.</p><p>This is much more predictable, flexible, and works on more versions of the OS than ImageRenderer.</p><p>Let’s walk through the why, how, and when.</p><h3>So why not just use ImageRenderer?</h3><p>Apple’s ImageRenderer is a way to natively convert SwiftUI views to images. It is clean and modern—but limited:</p><ul><li>Only works on iOS 16 and above.</li><li>The image creation happens off-screen, which means views will be rendered outside the visible interface tree.This can make it difficult to get proper layout timing — if your view hasn’t calculated its size or state yet, your image may be blank or the wrong image.</li><li>No animations or visual effects.Because the view has never been actually shown onscreen, anything that relies on being visible like transitions, shadows, or opacity-based effects will not work as expected.</li><li>You don’t get the option of exactly <strong>when</strong> to create a snapshot.You rely on SwiftUI events like .onAppear or .task which happen after layout but before the UI is visually rendered—leaving the possibility that images could be snapped <strong>before</strong> the view has updated or animations completed.</li></ul><p><strong>In this UIKit-backed world, you control when the snapshot happens and what the user is seeing at that moment in time.</strong></p><p>So it’s great for static rendering, but not preferable for real-world snapshots of active, live UI.</p><p>This solution uses UIKit’s drawHierarchy(in:afterScreenUpdates:) which captures <strong>what the user sees</strong> in front of them.</p><p>It’s stable, works with anything, and will consistently capture dynamic layouts.</p><h3>What does this (and why is it worth it)</h3><p><strong>The goal is straightforward</strong>: When a trigger becomes true, we render the view hierarchy to a UIImage, and then return it back via a closure.</p><ul><li>You maintain your SwiftUI layout.</li><li>You trigger the capturing process intentionally.</li><li>You get the image back on your terms.</li></ul><p>It is declarative, local to the view you care about, and better yet — it’s safe for reusing across your entire app.</p><h3>The code, and how it works</h3><h3>First, the API you will use:</h3><pre>extension View {<br>    @ViewBuilder<br>    func snapshot(trigger: Bool, onComplete: @escaping (UIImage) -&gt; ()) -&gt; some View {<br>        self<br>            .modifier(SnapshotModifier(trigger: trigger, onComplete: onComplete))<br>    }<br>}</pre><p>We wrap everything in a custom view modifier. Why? Because then we are able to keep the extension ergonomic, but still hook into the rendering lifecycle under the covers.</p><h3>Here’s what the modifier does:</h3><pre>fileprivate struct SnapshotModifier: ViewModifier {<br>    var trigger: Bool<br>    var onComplete: (UIImage) -&gt; ()<br>    @State private var view: UIView = .init(frame: .zero)<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .background(ViewExtractor(view: view))<br>            .compositingGroup()<br>            .onChange(of: trigger) { oldValue, newValue in<br>                generateSnapshot()<br>            }<br>    }<br>    private func generateSnapshot() {<br>        if let superView = view.superview?.superview {<br>            let render = UIGraphicsImageRenderer(size: superView.bounds.size)<br>            let image = render.image { _ in<br>                superView.drawHierarchy(in: superView.bounds, afterScreenUpdates: true)<br>            }<br>            onComplete(image)<br>        }<br>    }<br>}</pre><h3>So here’s what’s going on here:</h3><ul><li>@State private var view: Holds the reference to a UIView inside the SwiftUI view hierarchy.</li><li>.background(ViewExtractor(view: view)): Injects the UIView into the SwiftUI tree.</li><li>.compositingGroup(): Flattens rendering into a single layer. This is <strong>very important</strong> when capturing with drawHierarchy to ensure visual effects like opacity, shadows, and clipping are captured correctly.</li><li>.onChange(of: trigger): When the trigger turns true — snapshot!</li><li>generateSnapshot(): Uses UIKit’s UIGraphicsImageRenderer to draw the <strong>actual rendered</strong> view hierarchy into a bitmap.</li></ul><blockquote><strong><em>Key point:</em></strong><em> We use </em><em>view.superview?.superview instead of just </em><em>view.superview because SwiftUI wraps inserted UIViews in multiple invisible layers. The second superview usually represents the </em><strong><em>actual visible content</em></strong><em>.</em></blockquote><h3>And what is ViewExtractor?</h3><p>ViewExtractor is a tool that embeds a UIView in the SwiftUI hierarchy, creating an anchor — a physical UIView — we can later use to traverse the UIKit view tree to find the real rendered content.</p><p>We can’t get at the views directly, but this representable serves as our anchor into UIKit.</p><pre>fileprivate struct ViewExtractor: UIViewRepresentable {<br>    var view: UIView<br>    func makeUIView(context: Context) -&gt; UIView {<br>        view.backgroundColor = .clear<br>        return view<br>    }<br>    func updateUIView(_ uiView: UIView, context: Context) {<br>        // no process<br>    }<br>}</pre><p>It’s a little hack that gets our UIView into the SwiftUI layout so we can find and snapshot it later.</p><h3>How to use it</h3><p>Here’s how this works in a real view:</p><pre>struct SomeView: View {<br>    @State private var triggerSnapshot = false<br>    var body: some View {<br>        VStack {<br>            SomeComplexView()<br>                .snapshot(trigger: triggerSnapshot) { image in<br>                    saveOrShare(image)<br>                }<br>            // You provide the timer, you get a UIImage, your usage of SwiftUI remains clean<br>            Button(&quot;Capture View&quot;) {<br>                triggerSnapshot = true<br>            }<br>        }<br>    }<br>}</pre><h3>Advantages</h3><ul><li><strong>Declarative:</strong> Very SwiftUI-like.</li><li><strong>Reusable:</strong> Just drop it into any view — no layout hacks or global state.</li><li><strong>Lightweight:</strong> No libraries.</li><li><strong>Predictable:</strong> You explicitly control the snapshot.</li><li><strong>Compatible:</strong> Works on logic older than iOS 13.</li><li><strong>More Reliable Than </strong>ImageRenderer<strong>:</strong> Captures full view with dynamic contents, animations, etc.</li></ul><h3>Final words (aka what could go wrong)</h3><p>This isn’t magic — it’s UIKit under the hood. The UIView you extract may not always be where you expect if your layout is deeply nested or inside complex SwiftUI containers.</p><p>You may need to modify the superviews approach (.superview?.superview) depending on your layout setup.</p><p>But from a <strong>reusable pattern</strong> perspective?</p><p><strong>Rock solid</strong>, in almost every scenario.</p><p>We grab what is visible to the user, without affecting the SwiftUI design.</p><p>Once you implement it in one place, you’ll soon find all kinds of uses to implement it everywhere.</p><h3>Want more of this?</h3><p>This is the kind of practical, project-based snippet we believe in at <a href="https://justdoswift.substack.com/"><strong>Just Do Swift</strong></a>.</p><p>We want to help devs like you solve real problems, build better applications, all while getting to the point and not wasting time on other fluff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2be6f66eba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take Full Control: Working with the Photo Library in SwiftUI]]></title>
            <link>https://medium.com/@justdoswift/take-full-control-working-with-the-photo-library-in-swiftui-4f20d51e931e?source=rss-3197a4eecb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f20d51e931e</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[photos]]></category>
            <dc:creator><![CDATA[Just Do Swift]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 12:49:37 GMT</pubDate>
            <atom:updated>2025-06-11T12:49:37.755Z</atom:updated>
            <content:encoded><![CDATA[<p>Go Beyond the Default: Unlock Full Photo Library Access in SwiftUI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CopJ-UUO45tPKvuG.png" /></figure><p>You want more than what the standard Apple provided photo picker gives you.</p><p>You want the ability to save, delete, filter, and favorite photos however you like in your app.</p><p>Here is how you can do it.</p><h3>1. Present the System Photo Picker (the “easy button”)</h3><p>The easiest way in is through .photosPicker, which in a few lines of code, allows the user to pick photos from their library:</p><pre>.photosPicker(<br>    isPresented: $isPhotosPickerPresented,<br>    selection: $photos,<br>    photoLibrary: PHPhotoLibrary.shared()<br>)</pre><p>That’s the SwiftUI way, for now let’s dig a little deeper.</p><h3>2. Save Images to the Photo Library (Programmatically)</h3><p>Want to allow users to save images generated through your app like memes, qr codes, etc that they generate, directly to their photo album?</p><p>All you need to do is call performChanges to the PHPhotoLibrary and pass it a PHAssetChangeRequest example:</p><pre>func addImageToPhotoLibrary(image: UIImage) {<br>    PHPhotoLibrary.shared().performChanges({<br>        PHAssetChangeRequest.creationRequestForAsset(from: image)<br>    }) { success, error in<br>        if success {<br>            print(&quot;Successfully saved to photo library.&quot;)<br>        } else if let error = error {<br>            print(&quot;Could not save image: \(error)&quot;)<br>        }<br>    }<br>}<br>Button(&quot;Add&quot;) {<br>    if let image = UIImage(named: &quot;demo&quot;) {<br>        addImageToPhotoLibrary(image: image)<br>    }<br>}</pre><p>No longer do you have to awkwardly show a share sheet. Tap, save, done.</p><h3>3. Delete Photos — Your Way</h3><p>Need to delete a photo from the library?</p><p>Here is how you can do it — using PHAssetChangeRequest.deleteAssets.</p><p>You <em>need</em> to pass a PHAsset reference, not a UIImage.</p><pre>func deleteAsset(asset: PHAsset) {<br>    PHPhotoLibrary.shared().performChanges({<br>        PHAssetChangeRequest.deleteAssets([asset] as NSArray)<br>    }) { success, error in<br>        if success {<br>            print(&quot;Photo deleted.&quot;)<br>        } else if let error = error {<br>            print(&quot;Failed to delete: \(error)&quot;)<br>        }<br>    }<br>}</pre><p>Let your users have a unique “Delete” experience depending on how your application behaves.</p><h3>4. Toggle favorites with a tap</h3><p>Sometimes that’s just a heart icon.</p><p>You can toggle the favorite status like so:</p><pre>func favorite(asset: PHAsset) {<br>    PHPhotoLibrary.shared().performChanges({<br>        let request = PHAssetChangeRequest(for: asset)<br>        request.isFavorite = !asset.isFavorite<br>    }) { success, error in<br>        if success {<br>            print(&quot;Toggled favorite.&quot;)<br>        } else if let error = error {<br>            print(&quot;Failed: \(error)&quot;)<br>        }<br>    }<br>}</pre><p>Build your own “Favorites” UI with no strings attached.</p><h3>5. Fetch and filter photos (Similar to Core Data)</h3><p>Want to fetch and display up to the latest 10 photos?</p><p>Or only show the photos created between certain dates?</p><p>Use PHAsset.fetchAssets--it&#39;s too flexible and powerful not to.</p><pre>func fetchAssets() {<br>    let fetchOptions = PHFetchOptions()<br>    fetchOptions.sortDescriptors = [NSSortDescriptor(key: &quot;creationDate&quot;, ascending: false)]<br>    let calendar = Calendar.current<br>    if let startDate = calendar.date(from: DateComponents(year: 2023, month: 1, day: 1)) {<br>        fetchOptions.predicate = NSPredicate(format: &quot;creationDate &gt;= %@&quot;, startDate as NSDate)<br>    }<br>    fetchOptions.fetchLimit = 10<br>    let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)<br>    fetchResult.enumerateObjects { asset, _, _ in<br>        self.assets.append(asset)<br>    }<br>}</pre><p>That’s it, you’re all done.</p><p>You have built the fundamentals of a “Latest Photos” grid or filter any way you feel.</p><h3>6. Create a UIImage from PHAsset to display</h3><p>Want to display a thumbnail?</p><p>Here’s how to create a UIImage from a PHAsset.</p><pre>func getThumbnail(for asset: PHAsset) -&gt; UIImage {<br>    let manager = PHImageManager.default()<br>    var thumbnail: UIImage = UIImage()<br>    let options = PHImageRequestOptions()<br>    options.isSynchronous = true<br>    manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: options) { result, _ in<br>        if let result = result {<br>            thumbnail = result<br>        }<br>    }<br>    return thumbnail<br>}</pre><p>Will work great for grid views and previews (less than seconds).</p><p><strong>Bottom line:</strong></p><p>Don’t let Apple’s defaults box you in. With these tools, you can create a fully customized photo experience for your app — save, delete, filter, favorite and display photos however your (and user) want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f20d51e931e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Image Handling in SwiftUI: From Assets to User Uploads and Beyond]]></title>
            <link>https://medium.com/@justdoswift/mastering-image-handling-in-swiftui-from-assets-to-user-uploads-and-beyond-e66a75c444f7?source=rss-3197a4eecb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e66a75c444f7</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Just Do Swift]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 15:14:25 GMT</pubDate>
            <atom:updated>2025-06-10T15:14:25.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4Emfu8To4hm0-dB6Fx0hg.png" /></figure><p>A Practical Guide to Loading, Transforming, and Uploading Images in Real-World iOS Apps</p><p>You’re building a tangible iOS application.</p><p>This means your images aren’t going to come only from your asset catalog.</p><p>Your users will provide images — either through a camera, photo library, or the network.</p><p>Many times you will need to compress, transform, upload, or render images from formats such as base64.</p><p>And while SwiftUI isn’t going to help you with any of this, it isn’t going to do any of it for you by default, either!</p><p>This is your all-in-one opportunity to manage all of these possibilities.</p><p>Real APIs. Real Data. Real SwiftUI.</p><p>Whether you are building a hobby application or a new App Store submission, it is important you understand image handling.</p><h3>Start simple: Your assets</h3><p>When your images are in your app bundle, you can use:</p><pre>Image(&quot;demo&quot;)</pre><p>When you call this, SwiftUI will find demo in your Assets catalog, regardless of raster format (PNG, JPEG, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ic53evfJ8OWf6ftS.png" /></figure><p>This is the quickest way to load your static images while maintaining device-level rendering consistency.</p><p>Just keep in mind that populating too many high resolution images in your Assets catalog may increase your app’s binary size.</p><p>Limit this approach to app images such as icons, logos, or placeholder graphics that you absolutely need.</p><h3>UIImage</h3><p>The Image(uiImage:) initializer provides access to UIKit from your SwiftUI interface.</p><p>This is your go-to method when you have images that came directly from user input:</p><pre>Image(uiImage: yourUIImage)</pre><p>It is very flexible, and it is the method you need when dealing with images taken or selected during runtime, too.</p><p>However, you rarely will be starting with a UIImage.</p><p>The system gives you either data or items from a picker — you’ll have to cross that bridge.</p><h3>Importing images from the photo library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*933KDRh7KZffQZAN.png" /></figure><p>In iOS 16 and later, SwiftUI offers a native photo picker called PhotosPicker.</p><p>When a user picks a photo, an associated PhotosPickerItem is returned, though the item cannot be used as-is.</p><p>Instead, it needs to be handled.</p><p><strong>Step 1: Convert </strong>PhotosPickerItem<strong> to </strong>Data</p><pre>let data = try await item.loadTransferable(type: Data.self)</pre><p>Take note that this async call “safely” loads the raw data of the photo.</p><p><strong>Step 2: Convert </strong>Data<strong> to </strong>UIImage</p><pre>let image = UIImage(data: data)</pre><p>At this point, you have an image and can call Image(uiImage:) in SwiftUI to show the image in your view hierarchy.</p><p>We can do this in a cleaner, more reusable fashion using extension methods:</p><pre>extension PhotosPickerItem {<br>    func convert() async -&gt; Data? {<br>        try? await self.loadTransferable(type: Data.self)<br>    }<br>    func convertUIImage() async -&gt; UIImage? {<br>        if let data = await convert() {<br>            return UIImage(data: data)<br>        }<br>        return nil<br>    }<br>}</pre><p>By having methods like these, you can write readable and concise logic when working with results of a photo picker.</p><h3>Taking photos with the camera</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DxL_oDxHV29FZFlq.png" /></figure><p>SwiftUI doesn’t yet have a native camera view, but UIKit does in the form of UIImagePickerController.</p><p>You can wrap it using UIViewControllerRepresentable so you can use it in your SwiftUI views:</p><pre>struct CameraView: UIViewControllerRepresentable {<br><br>    @Binding var image: UIImage?<br>    @Environment(\.dismiss) var dismiss<br><br>    func makeUIViewController(context: Context) -&gt; UIImagePickerController {<br>        let picker = UIImagePickerController()<br>        picker.sourceType = .camera<br>        picker.delegate = context.coordinator<br>        return picker<br>    }<br><br>    func updateUIViewController(_: UIImagePickerController, context: Context) {}<br><br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(self)<br>    }<br><br>    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {<br><br>        let parent: CameraView<br><br>        init(_ parent: CameraView) {<br>            self.parent = parent<br>        }<br><br>        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {<br>            parent.image = info[.originalImage] as? UIImage<br>            parent.dismiss()<br>        }<br><br>        func imagePickerControllerDidCancel(_: UIImagePickerController) {<br>            parent.dismiss()<br>        }<br>    }<br>}</pre><p>With the above call, when the photo is taken, the result will be in your @Binding and will be immediately accessible in SwiftUI.</p><h3>Uploading: transform UIImage to Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lCYjj6d1j7E55pKS.png" /></figure><p>Most APIs expect images sent to them as Data. Given you have a UIImage, you can transform it to data in order to be uploaded:</p><pre>let data = image.jpegData(compressionQuality: 0.8)</pre><p>Reduce compressionQuality to lower the file size.</p><p>Alternatively, if you want to keep the resolution and use non-lossy compression:</p><pre>let data = image.pngData()</pre><p>Once you have the Data, you can use it to upload the image to your server.</p><p>Here’s a very basic example using URLSession to upload an image to the endpoint:</p><pre>func uploadImage(data: Data, to url: URL) async throws {<br>    var request = URLRequest(url: url)<br>    request.httpMethod = &quot;POST&quot;<br>    request.setValue(&quot;application/octet-stream&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    request.httpBody = data<br>    let (responseData, response) = try await URLSession.shared.data(for: request)<br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        throw URLError(.badServerResponse)<br>    }<br>    // You can do something with responseData here if need to<br>    print(&quot;Upload completed, response from server: \(responseData)&quot;)<br>}</pre><p>In a production app, you may need to send authentication headers or wrap the image in a multipart form data request, but that depends on what is required by your server to receive files.</p><p>However, this should serve as a basic representation of functionality related to sending image bytes to a backend.</p><h3>Downloading: Data to UIImage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pyer6BIH8x6SDPpo.png" /></figure><p>If your backend directly sends image bytes, you can create a displayable image from those bytes with:</p><pre>let image = UIImage(data: downloadedData)</pre><p>Here’s a more detailed example of downloading image data from a URL and creating a UIImage from it:</p><pre>func downloadImage(from url: URL) async throws -&gt; UIImage? {<br>    let (data, response) = try await URLSession.shared.data(from: url)<br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        throw URLError(.badServerResponse)<br>    }<br>    return UIImage(data: data)<br>}</pre><p>Once you have a UIImage, you can use Image(uiImage:) in SwiftUI.</p><p>This pattern will allow you to easily download dynamic content, remote avatars, thumbnails or off-the-shelf resources located on CDNs.</p><h3>Base64 Encoding and Decoding</h3><p>If you’re working with base64 strings for your API (which is quite common), you can convert to and from like this:</p><pre>// Encode<br>let base64String = imageData.base64EncodedString()<br>// Decode<br>if let data = Data(base64Encoded: base64String) {<br>    let image = UIImage(data: data)<br>    // Display the image or however else you want to use it<br>}</pre><p>If you want to upload base64 to a server as part of a JSON payload, you can do this:</p><pre>func uploadBase64Image(base64String: String, to url: URL) async throws {<br>    var request = URLRequest(url: url)<br>    request.httpMethod = &quot;POST&quot;<br>    request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    let body: [String: String] = [&quot;image&quot;: base64String]<br>    request.httpBody = try JSONEncoder().encode(body)<br>    let (_, response) = try await URLSession.shared.data(for: request)<br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        throw URLError(.badServerResponse)<br>    }<br>}</pre><p>If you want to download and decode a base64 image string from the server, you can do something like this:</p><pre>func downloadBase64Image(from url: URL) async throws -&gt; UIImage? {<br>    let (data, response) = try await URLSession.shared.data(from: url)<br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        throw URLError(.badServerResponse)<br>    }<br>    let decoded = try JSONDecoder().decode([String: String].self, from: data)<br>    if let base64 = decoded[&quot;image&quot;], let imageData = Data(base64Encoded: base64) {<br>        return UIImage(data: imageData)<br>    }<br>    return nil<br>}</pre><p>You often see base64 in APIs that return images as JSON blobs.</p><p>Base64 is a useful way to upload images when you cannot do binary transfer, but it’s important to remember that base64 adds ~33% overhead and will increase your memory usage.</p><h3>Compressing Images Under a Size Limit</h3><p>If you need to make sure files are under a certain size (say, under 5MB), you can use an iterative compression algorithm:</p><pre>extension Data {<br>    func compressTo(maxSizeKB: Int, compressionStep: CGFloat = 0.1) -&gt; Data? {<br>        guard let image = UIImage(data: self) else { return nil }<br>        var quality: CGFloat = 1.0<br>        var compressed = image.jpegData(compressionQuality: quality)<br>        while let data = compressed, data.count &gt; maxSizeKB * 1024, quality &gt; 0 {<br>            quality -= compressionStep<br>            compressed = image.jpegData(compressionQuality: quality)<br>        }<br>        return compressed<br>    }<br>}</pre><p>How It Works:</p><ul><li>The function starts by converting the Data object to a UIImage.</li><li>Then it compresses the image by applying JPEG compression in increments, decreasing quality by a small amount (default: 0.1) until the data is less than the target size.</li><li>The process can be terminated either when the image is small enough or the quality reaches zero.</li></ul><p>This approach gives you a knob that you can tune for fidelity versus size.</p><p>Essential when you have file uploads with limits.</p><h3>CIImage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*efVsaQyHEIWlOBoi.png" /></figure><p>CIImage is a Core Image asset for processing images through a high-performance pipeline.</p><p>You do not use it as an image for rendering.</p><p>You use it to apply filters, chain effects to images, or build your own processing pipeline.</p><p>To create a CIImage from a UIImage:</p><pre>let ciImage = CIImage(image: uiImage)</pre><p>To apply a Core Image filter:</p><pre>let filter = CIFilter(name: &quot;CISepiaTone&quot;)!<br>filter.setValue(ciImage, forKey: kCIInputImageKey)<br>filter.setValue(0.8, forKey: kCIInputIntensityKey)<br>let output = filter.outputImage</pre><p>To convert from a CIImage to UIImage (for rendering in SwiftUI):</p><pre>let context = CIContext()<br>if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {<br>    let resultImage = UIImage(cgImage: cgImage)<br>}</pre><blockquote><em>In this example, </em><em>CIContext has been responsible to rendering the </em><em>CIImage out into a </em><em>CGImage.</em></blockquote><blockquote><em>Core Image itself is lazy; it defines image operations but never executes them until rendering.</em></blockquote><blockquote><em>A </em><em>CGImage is a concrete representation of the pixel data and will be available to you once converted.</em></blockquote><blockquote><em>The </em><em>UIImage wraps this back into UIKit and SwiftUI.</em></blockquote><p>Use this when you are creating real-time effects and image transformations, or anything straight from the camera.</p><h3>CGImage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jl2sQg9zgT9d5V-p.jpeg" /></figure><p>CGImage is a low level, pixel-based image representation primarily used in Core Graphics.</p><p>Unlike CIImage, which is more abstract, less pixel-oriented, and more appropriate for processing images, CGImage allows you direct access to the pixels.</p><p>Obtain a CGImage from a UIImage:</p><pre>let cgImage = uiImage.cgImage</pre><p>Convert a CGImage back to a UIImage:</p><pre>let uiImage = UIImage(cgImage: cgImage)</pre><p>Convert a CIImage to CGImage:</p><pre>let context = CIContext()<br>let cgImage = context.createCGImage(ciImage, from: ciImage.extent)</pre><p>Use a CGImage in SwiftUI:</p><pre>if let cgImage = cgImage {<br>    let image = Image(decorative: cgImage, scale: 1.0)<br>}</pre><p>Both CGImage is useful in situations where control over performance and pixel access is to be had like when you want to generate a thumbnail or perform transforms without automatic abstraction.</p><h3>AsyncImage</h3><p>AsyncImage is a SwiftUI-native view class, since iOS 15, to download and display remote images.</p><p>Basic use:</p><pre>AsyncImage(url: URL(string: &quot;https://example.com/avatar.png&quot;))</pre><p>You can customize its appearance with loading and error states:</p><pre>AsyncImage(url: imageURL) { phase in<br>    switch phase {<br>    case .empty:<br>        ProgressView()<br>    case .success(let image):<br>        image.resizing()<br>    case .failure:<br>        Image(systemName: &quot;photo&quot;)<br>    @unknown default:<br>        EmptyView()<br>    }<br>}</pre><p>AsyncImage is the simplest way to download and display an image when your requirement is relatively simple, i.e., display profile images, thumbnails, or image assets from a CDN and want to do so in the least amount of code.</p><p>when your application needs to do more than fetch and display an image, AsyncImage starts to feel quite limiting.</p><p>Here’s the reality check:</p><ul><li>No built-in image caching! Each reload is another network call.</li><li>Don’t even think about customizing request headers, cache policies, retries…. AsyncImage doesn’t do any of that.</li><li>Customizing placeholders/loading states? The options are minimal.</li></ul><p>If your project requires real-world flexibility — intelligent caching, robust networking, rich image processing — AsyncImage isn’t going to cut it.</p><p>Enter Kingfisher or SDWebImage.</p><p>Great libraries for developers who need control: full-caching, customizable networking, and a developer toolkit for everything from placeholders to progressive loading.</p><p>Or, if you really want control, build your own loader using URLSession.</p><p>Whether you’re just getting started or optimizing code in production, we’re all learning and improving together.</p><p>This guide is meant to help you solve real problems — and to be a starting point for sharing, discussion, and growth as a community.</p><p>Let’s explore, learn, and build better products together — so every user benefits from what we create.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e66a75c444f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom fonts in SwiftUI: A practical guide to standing out]]></title>
            <link>https://medium.com/@justdoswift/custom-fonts-in-swiftui-a-practical-guide-to-standing-out-f1a50245cee3?source=rss-3197a4eecb20------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1a50245cee3</guid>
            <category><![CDATA[fonts]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[custom]]></category>
            <dc:creator><![CDATA[Just Do Swift]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 15:46:01 GMT</pubDate>
            <atom:updated>2025-06-08T15:46:01.452Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Custom fonts do more than just add decoration.</strong> They provide your app a voice and a style.</p><p>If you expect your iOS app to be different, or if the product simply deserves some personality, the default system fonts are not going to cut it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgK2yxyF3fgJUHMIP_30Hg.jpeg" /></figure><p>Here’s how to embed and utilize custom fonts in SwiftUI without losing your mind.</p><p>If you’ve ever asked yourself why your font simply won’t show up, or you want your app to look like someone cared about it, keep reading.</p><h3>Managing the font files: Why organizing is important</h3><p>When you drag your .ttf or .otf file into Xcode, don’t just drop it anywhere.</p><p>Add a “Fonts” group/folder in your project folder to keep things organized.</p><p>It’s also a good idea to check <strong>Build Phases</strong> under <strong>Copy Bundle Resources</strong> just to make sure your font(s) are in there.</p><p>If your font isn’t included, your app won’t use it. Make sure to use lowercase, hyphenated filenames like <strong>inter-regular.ttf</strong>to avoid case-sensitivity issues.</p><h3>Register your font in Your Info.plist</h3><p>iOS isn’t going to assume anything about what fonts you want.</p><p>Open up your <strong>Info.plist</strong> file and add the UIAppFonts key.</p><p>Under this key you will need to add each font filename (not the display name).</p><p>For example:</p><pre>Exile-Regular.ttf</pre><p>In Xcode this key will be shown as <strong>Fonts provided by application</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CU2z6ZC_u0-51EkF" /></figure><p>When you add a new entry it will be listed as Key and then under the property list editor it is labeled exactly that way.</p><p>Ensure that each filename matches, including the exact casing and extension.</p><blockquote><em>If you miss this step, Xcode is not going to complain to you about adding a font. Your app is just going to pretend your fonts do not exist and go about its business.</em></blockquote><h3>Identifying the true font name.</h3><p>The name of the filename is <strong>not necessarily</strong> the name you would use in code.</p><p>To get the internal font name you can execute the following:</p><pre>for family in UIFont.familyNames.sorted() {<br>    print(&quot;Family: \(family)&quot;)<br>    for name in UIFont.fontNames(forFamilyName: family) {<br>        print(&quot; - \(name)&quot;)<br>    }<br>}</pre><p>Run it one time and include your font. Then copy the font name exactly as the output.</p><p>The code prints all font families and names available to your app.</p><p>The output will look like:</p><pre>Family: Inter<br> - Inter-Regular<br> - Inter-Bold<br>Family: Helvetica Neue<br> - HelveticaNeue<br> - HelveticaNeue-Bold</pre><p>You need the exact string for <strong>.font(.custom(“Inter-Bold”, size: 16))</strong>.</p><p>If you don’t get the name specific, SwiftUI will fallback quietly to the system font as though nothing happened.</p><h3>Dynamic Type and scaling with .custom() fonts</h3><p>Let’s start with a basic example of using a custom font in SwiftUI:</p><pre>Text(&quot;Hello World&quot;)<br>   .font(.custom(&quot;Exile&quot;, size: 20))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bwn_P9mIzfYg9mSv.png" /></figure><p>If you use .custom() with just a size (20), your font will still scale to the user&#39;s Dynamic Type settings — it will always respect the scale curve for .body regardless of where it&#39;s used.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1091583453%3Fh%3D57d9273420%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1091583453%2F57d9273420&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2024453847-4575d12d3715f23bd1790dbed3c825962b22aed724ab7e1a80ff1480a5dcf894-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/81aa32770e1a6f3cdff4432199b91f49/href">https://medium.com/media/81aa32770e1a6f3cdff4432199b91f49/href</a></iframe><p>If you’d like your custom font to also scale like an alternate system text style such as .headline, .title, or .caption, you will include the relativeTo parameter:</p><pre>Text(&quot;Hello World&quot;)<br>  .font(.custom(&quot;Exile&quot;, size: 20, relativeTo: .headline))</pre><p>Use relativeTo when you want your custom font to scale similarly to a specific system style.</p><p>If you leave it out, it’s .body by default.</p><p>This gives you control over your fonts and still allows your UI to visually respect the rest of iOS.</p><h4>Using text styles instead of fixed sizes for custom fonts</h4><p>SwiftUI has a number of built-in text styles, such as .title, .body, and .caption, that give your app a native feel, and respond to the user’s Dynamic Type settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3kMnsibP9VzdeP0.png" /></figure><p>But if you use custom fonts, you often end up hardcoding point sizes, or repeating font logic throughout your codebase.</p><p>So there’s got to be a better way.</p><p>To solve this problem, you’ll want to do a couple of things.</p><ul><li>First, wrap your font selection in an extension so that you can leverage one, consistent API everywhere, and don’t need to repeat font names or configuration in every view. This keeps your codebase clean, and it gives you the capability to change your font logic in one place.</li><li>Second, instead of hardcoding, use UIFont.preferredFont(forTextStyle:) to retrieve what the system recommends for each text style based on their settings. This way, your custom font’s scaling, accessibility, and feel will always match the system’s.</li></ul><p>Now let’s see how to put it all together:</p><pre>extension Font {<br>    static func exile(_ textStyle: Font.TextStyle) -&gt; Font {<br>        // Use the internal name of your font file<br>        let name = &quot;Exile-Regular&quot;<br>        // Get the exact point size for the current text style<br>        let size = UIFont.preferredFont(forTextStyle: textStyle.toUIFontTextStyle()).pointSize<br>        // Return the custom font sized and scaled just like system text<br>        return .custom(name, size: size, relativeTo: textStyle)<br>    }<br>}</pre><pre>extension Font.TextStyle {<br>    func toUIFontTextStyle() -&gt; UIFont.TextStyle {<br>        switch self {<br>        case .largeTitle: return .largeTitle<br>        case .title: return .title1<br>        case .title2: return .title2<br>        case .title3: return .title3<br>        case .headline: return .headline<br>        case .body: return .body<br>        case .callout: return .callout<br>        case .subheadline: return .subheadline<br>        case .footnote: return .footnote<br>        case .caption: return .caption1<br>        case .caption2: return .caption2<br>        @unknown default: return .body<br>        }<br>    }<br>}</pre><h4>Here’s how this pattern works in practice:</h4><ul><li><strong>You use a style, not a number:</strong> When you call .exile(.body), you’re asking SwiftUI for your custom font, at exactly the same size the system would use for .body on this device.</li><li><strong>No hardcoded sizes:</strong> The extension automatically looks up the right point size for each text style using UIFont.preferredFont(forTextStyle:). This keeps your UI in sync with any accessibility or Dynamic Type settings.</li><li><strong>Scaling just works:</strong> Because you’re passing the text style to relativeTo, your custom font always scales like system text.</li></ul><p>So, you never have to specify a number. Your font always matches user expectations. Your UI looks clean, accessible, and native — everywhere.</p><p>Now, to use it, your code is just:</p><pre>Text(&quot;Body text&quot;)<br>    .font(.exile(.body))</pre><pre>Text(&quot;Big title&quot;)<br>    .font(.exile(.largeTitle))</pre><p>This approach keeps your font code simple and ensures your custom font will always “just work.”</p><h3>Loading fonts at runtime: For themes, small app sizes, or remote updates</h3><p>Bundled fonts are perfectly fine, but sometimes you need to load the font from the web for user themes, smaller app sizes, or deliver new styles without having to rely on updates.</p><p>To begin loading the font, simply download it:</p><pre>func downloadFont(from url: URL, completion: @escaping (URL?) -&gt; Void) {<br>    // destination URL on the user&#39;s device<br>    URLSession.shared.downloadTask(with: url) { localURL, _, error in<br>        guard let localURL = localURL else {<br>            print(&quot;Download failed: \(error?.localizedDescription ?? &quot;Unknown error&quot;)&quot;)<br>            completion(nil)<br>            return<br>        }<br>        completion(localURL)<br>    }.resume()<br>}</pre><h4>What type of remote file can you use?</h4><p>When loading remote fonts from the web, make sure your remote URL is a direct link to standard font file, such as a .ttf(TrueType Font) or .otf (OpenType Font).</p><p>For example:</p><pre>https://your.cdn.com/fonts/inter-regular.ttf<br>https://your.cdn.com/fonts/Roboto-Bold.otf<br>https://your.cdn.com/fonts/Exile-Regular.ttf</pre><p>Make sure you are not loading a zip archive or encoded data — Swift and iOS expect a direct encountered font file.</p><p>This will ensure that your registerFont functions be able to download and use your font without any additional steps, or errors.</p><p>Then, you’ll register the font.</p><p><strong>For iOS 18 and greater:</strong></p><pre>import CoreText</pre><pre>func registerFont(url: URL) {<br>    var error: Unmanaged&lt;CFError&gt;?<br>    let success = CTFontManagerRegisterFontsForURL(url as CFURL, .process, &amp;error)<br>    if success {<br>        print(&quot;Font registered successfully.&quot;)<br>    } else {<br>        let description = (error?.takeUnretainedValue() as Error?)?.localizedDescription ?? &quot;Unknown error&quot;<br>        print(&quot;Failed to register font: \(description)&quot;)<br>    }<br>}</pre><p><strong>For iOS 17 and less:</strong></p><pre>func registerFontLegacy(url: URL) {<br>    guard let data = try? Data(contentsOf: url),<br>        let provider = CGDataProvider(data: data as CFData),<br>        let font = CGFont(provider) else { return }<br>    var error: Unmanaged&lt;CFError&gt;?<br>    CTFontManagerRegisterGraphicsFont(font, &amp;error)<br>}</pre><h4>How font registration works</h4><p>Once your app downloads a font file from a remote URL, it’s not immediately usable — you need to register it with iOS.</p><p>Font registration tells the system, “This font is now available for my app to use.”</p><ul><li>On iOS 18 and greater, CTFontManagerRegisterFontsForURL allows you to register a font file from the local file system URL.</li><li>On iOS 17 and below, registration is done by loading the font data into memory and calling CTFontManagerRegisterGraphicsFont.</li></ul><blockquote><em>SwiftUI only checks for custom fonts when the view is created.</em></blockquote><blockquote><em>If your font is not registered by the time SwiftUI is checking, </em><strong><em>it will quietly use the system font and never attempt to check for the custom font again</em></strong><em>.</em></blockquote><p><strong>Make sure the font is downloaded and registered before displaying any views that use the font.</strong></p><p>Show a loading indicator while the font is preparing.</p><p>Only show your main content when the font is available.</p><p>This way the user’s experience never gets set back on an inappropriate fallback.</p><pre>@State private var fontIsReady = false</pre><pre>var body: some View {<br>    Group {<br>        if fontIsReady {<br>            Text(&quot;Loaded at runtime&quot;)<br>                .font(.custom(&quot;YourFontName&quot;, size: 20))<br>        } else {<br>            ProgressView(&quot;Loading font…&quot;)<br>        }<br>    }<br>    .onAppear {<br>        // Example: Put your remote .ttf or .otf<br>        downloadFont(from: URL(string: &quot;https://your.cdn.com/fonts/inter-regular.ttf&quot;)!) { localURL in<br>            guard let localURL = localURL else { return }<br>            if #available(iOS 18, *) {<br>                registerFont(from: localURL)<br>            } else {<br>                registerFontLegacy(from: localURL)<br>            }<br>            fontIsReady = true<br>        }<br>    }<br>}</pre><p>In this example, downloadFont fetches a remote .ttf or .otf font file.</p><p>The registration function makes the font available to your app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1091584133%3Fh%3D178183914c%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1091584133%2F178183914c&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2024454639-65bc4f700460ba5c6faaf0208efc7d90b4a4343a19c476d26b9d195c54cca2ff-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/d836b08e198c0a15f8e581694979bb80/href">https://medium.com/media/d836b08e198c0a15f8e581694979bb80/href</a></iframe><blockquote><em>Only after the font is downloaded and registered do you show your main content — that way your custom font always displays correctly without a fallback to the system font.</em></blockquote><h3>Where developers go to find high-quality, legal fonts for iOS</h3><p>The right font can help set your app apart. Here’s where developers find quality fonts with reasonable licensing for mobile apps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x3LrpjteAiOUxE2a.png" /></figure><blockquote><em>Always double check the individual licenses before you ship a commercial app. Lawyers are more boring than fonts.</em></blockquote><h3>Why you don’t bundle every font…</h3><p>Fonts look small, but they add up.</p><p>A single .ttf or .otf is going to be 200–400 KB on average, and that is just one style.</p><p>If your app supports different weights or languages, each is its own file.</p><p>If you bundle 10 styles over three languages you are going to add a significant few megabytes.</p><p><strong>App size matters.</strong></p><p>Large bundles mean longer downloads, less install rates, and possibly App Store review headaches.</p><p>Most people will never use all of those custom fonts and you are requiring everyone to pay for a handful of edge cases.</p><p><strong>The better option</strong>: only package the fonts and styles that your app actually uses.</p><p>If your users want more — maybe they want to create their own themes.</p><p>If an app user wants a rare language or brand, let them download those fonts on demand and cache them.</p><p>Your app will be appropriately fast and lean and power users still get to obfuscate their brand.</p><h3>The bigger picture</h3><p>Custom fonts may seem like a small detail in your app, but they make a clear statement: you care about polish and user experience.</p><p>Not everyone pays attention to these small details — but you do.</p><p>You want your work to be special, and you want your app to feel intentional and one-of-a-kind.</p><p>If you enjoyed this guide, please consider subscribing to our newsletter.</p><p>You will receive more practical SwiftUI and iOS tips like this one — focused on real projects, useful code, and building applications that are truly special.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1a50245cee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>