<?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 Danielcrompton on Medium]]></title>
        <description><![CDATA[Stories by Danielcrompton on Medium]]></description>
        <link>https://medium.com/@danielcrompton5?source=rss-c26e14afc8c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o34fUlzsPKYUqaA6</url>
            <title>Stories by Danielcrompton on Medium</title>
            <link>https://medium.com/@danielcrompton5?source=rss-c26e14afc8c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 06:08:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielcrompton5/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[SwiftUI video & audio player with PiP & Now Playing support]]></title>
            <link>https://medium.com/@danielcrompton5/swiftui-video-audio-player-with-pip-now-playing-support-5b0b67da0db5?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b0b67da0db5</guid>
            <category><![CDATA[video-player]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[audio]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 21:33:01 GMT</pubDate>
            <atom:updated>2026-03-28T21:35:03.533Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a multimedia player that works with both audio &amp; video for iOS, with features including allowing full-screen &amp; PiP, and publishing data to the now playing info center.</h4><h4>Introduction</h4><p>Hi there, I hope you 🫵 yes you, are having an awesome day and are in good health! My latest iOS development project is a <strong>YouTube ad remover</strong> that downloads videos locally &amp; plays them back. It’s teaching me a ton and my goal is to write guides on the things that confused me the most so you can learn as well! It will be finished soon and on Github.</p><p><strong>I’ll be giving plenty of documentation</strong> as we go through that supports my research. Please read it and experiment yourself if you want a deep understanding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*WmqTVU0OknuXkTZram_u1A.gif" /></figure><p>Before I start, I’ll <strong>download a short YouTube video</strong> and embed it into an Xcode project.</p><p>There are 3 stages I want to do:</p><ol><li>Setup the basic video player</li><li>Create presentation mode management</li><li>Configure for PiP &amp; background mode</li><li>Add metadata to the Now Playing info center</li><li>Make it work for audio playing as well</li></ol><h3>#0 — Preparing a video for demonstration</h3><p>While we develop this project, we need a video to preview things with. I’ll <strong>download a short YouTube video</strong> — a <a href="https://www.youtube.com/watch?v=NJsa6-y4sDs">Celine Dion song</a> from my recommended list will do the job! Obviously, this is a form of piracy and you should use a royalty free video in practice, so do as I say, not as I do…</p><p>If you don’t have <a href="https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#format-selection-examples">YT-DLP</a> downloaded, download it with brew: brew install yt-dlp then download the video with <strong>yt-dlp</strong> -o “Desktop/<strong>movie.mp4</strong>” -f <strong>“bv[ext=mp4]*+ba[ext=m4a]/b”</strong> --write-auto-subs <strong>--embed-subs</strong> <strong>--write-thumbnail</strong> “https://www.youtube.com/watch?v=NJsa6-y4sDs&quot;</p><ul><li>-o “Desktop/movie.mp4” → Specify the output path for the video</li><li>-f → Determine the format for the video</li><li>“bv[ext=mp4]*+ba[ext=m4a]/b” → <em>bv</em> means best video, <em>ba</em> means best audio. The square brackets add filters, so in this case look for the best video with an extension (represented by ext) and best audio with extension m4a and combine them (purpose of +)</li><li>--write-auto-subs --embed-subs → Download the automatically generated subtitles and embed them into the file rather than writing them to disk as a separate file. This makes thrm available in the video player:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*s6QnAS3qzUVmaWSO94CYOQ.png" /></figure><ul><li>--write-thumbnail → Download the thumbnail and write to disk (you could embed it into the file if you wanted with --embed-thumbnail)</li></ul><p>Later on in this guide, I’ll show you how to create the audio player as well, so for this, let’s use <a href="https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#format-selection-examples">yt-dlp</a> to download the audio from that video as well (much easier, just using the -x flag: yt-dlp -o “Desktop/<strong>audio.mp3</strong>” <strong>-x --audio-format mp3</strong> “https://www.youtube.com/watch?v=NJsa6-y4sDs&quot;</p><h3>#1 — Setup the basic video player</h3><p>I have <strong>added the video &amp; audio downloaded</strong> in the previous stage to a new Xcode project you can view on Github.</p><p>In the SwiftUI &amp; <a href="https://developer.apple.com/documentation/avkit/playing-video-content-in-a-standard-user-interface">AVKit</a> bridge, <a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-play-movies-with-videoplayer">we have a </a><a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-play-movies-with-videoplayer">VideoPlayer</a> view that takes input of an AVPlayer and represents a very <strong>simple and limited</strong> inline video player. We have literally no more control over its presentation or any attributes — and no specialized modifiers too. It <strong>doesn’t have a full-screen button</strong> so you’re limited to having it in inline mode only, no PiP mode enabled, and no metadata is published in the now playing info center.</p><pre>import SwiftUI<br>import AVKit<br><br>struct ContentView: View {<br>    @State private var player: AVPlayer?<br>    <br>    var body: some View {<br>        VStack {<br>            if let player {<br>                VideoPlayer(player: player)<br>                    .aspectRatio(16/9, contentMode: .fit)<br>            } else {<br>                Text(&quot;Cannot load video&quot;)<br>            }<br>        }<br>        .onAppear {<br>            let url = Bundle.main.url(/service/forresource: &quot;movie&quot;, withExtension: &quot;mp4&quot;)!<br>            player = AVPlayer(url: url)<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*TijKzkICim-WPM1uTKMWYQ.png" /></figure><p>The more complete/customizable way of creating a video player is by <a href="https://medium.com/@gokhanmutlu/implementing-picture-in-picture-pip-with-swiftui-ae1a0ae18939">using an <strong>AVPlayerViewController (which is UIKit-based) and putting it into a SwiftUI context with UIViewControllerRepresentable</strong></a>. You have a property to control whether the full-screen mode is enabled &amp; its button shows, one to control whether PiP is enabled, and fine grained access of its player &amp; overlay view.</p><p>Create MyVideoPlayer and replace usage of VideoPlayer with it in the Content View. Already you can see <strong>we have the full-screen button</strong> that SwiftUI “turned off” for some reason.</p><pre>import SwiftUI<br>import AVKit<br><br>struct MyVideoPlayer: UIViewControllerRepresentable {<br>    <br>    let player: AVPlayer<br>    <br>    private let playerController = AVPlayerViewController()<br>    <br>    func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>        playerController.player = player<br>        return playerController<br>    }<br>    <br>    // Called when the properties are updated by users of MyVideoPlayer to update the underlying AVPlayerViewController<br>    // In this case, there is no properties that should update this so it will remain empty &amp; emitted.<br>    func updateUIViewController(_ avPlayerViewController: AVPlayerViewController, context: Context) {<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*BbZmw-t-DgqAWH6cBkhZ3Q.png" /></figure><h3>#2 — Create presentation mode management</h3><p>Our new player can go into full-screen, PiP and inline mode, and we have delegate methods that tell us when it changes mode. It would be a good idea to (although not essential for lots of usages) to have the presentation mode communicated to usages of MyVideoPlayer, so they can adjust their UI. This <strong>section is skippable</strong>.</p><p>Create an enum to represent the possible states the video player can be in and pass a binding to it from the content view. <strong>Only the additions to files are shown from now on</strong>.</p><pre>struct ContentView: View {<br>    @State private var presentationMode = VideoPlayerPresentationMode.inline<br>    MyVideoPlayer(player: player, presentationMode: $presentationMode)<br>}<br><br>enum VideoPlayerPresentationMode: Sendable {<br>    case inline, pip, fullScreen<br>}<br><br>struct MyVideoPlayer: UIViewControllerRepresentable {<br>    let player: AVPlayer<br>    @Binding var presentationMode: VideoPlayerPresentationMode<br>}</pre><p>As stated before, nothing goes in the updateUIViewController method — our new binding is only for passing changes from MyVideoPlayer to users, not for MyVideoPlayer‘s internal player controller to respond to changes in the binding.</p><p>Next, the MyVideoPlayer internal video <a href="https://developer.apple.com/documentation/avkit/avplayerviewcontrollerdelegate">player controller should be assigned a delegate</a>: we can add a coordinator class for this. The coordinator definitely needs the binding for read-write access to the MyVideoPlayer presentation mode.</p><pre>struct MyVideoPlayer: UIViewControllerRepresentable {<br>    func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>        playerController.player = player<br>        playerController.delegate = context.coordinator // 👈<br>        return playerController<br>    }<br><br>    // MARK: Coordinator<br>    <br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(presentationState: $presentationMode)<br>    }<br>    <br>    // The coordinator can be accessed from any thread but the presentation state can only be accessed from the main actor.<br>    // Therefore the delegate methods for AVPlayerViewControllerDelegate must also be isolated on the main actor<br>    class Coordinator: NSObject, @MainActor AVPlayerViewControllerDelegate {<br>        <br>        @MainActor @Binding private var presentationState: VideoPlayerPresentationMode<br>                <br>        init(presentationState: Binding&lt;VideoPlayerPresentationMode&gt;) {<br>            self._presentationState = presentationState<br>        }<br>        <br>        // Full-screen<br>        <br>        @MainActor public func playerViewController(<br>            _ playerViewController: AVPlayerViewController,<br>            willBeginFullScreenPresentationWithAnimationCoordinator coordinator: any UIViewControllerTransitionCoordinator<br>        ) {<br>            coordinator.animate(alongsideTransition: nil) { _ in<br>                self.presentationState = .fullScreen<br>            }<br>        }<br>        @MainActor public func playerViewController(<br>            _ playerViewController: AVPlayerViewController,<br>            willEndFullScreenPresentationWithAnimationCoordinator coordinator: any UIViewControllerTransitionCoordinator<br>        ) {<br>            // When the app is closed and PiP begins, pipWillEnter and pipDidEnter both call before the full screen closes (this calls)<br>            // To avoid setting the state to inline when PiP enters (and the full screen ends) make sure we are not already in PiP mode<br>            if presentationState == .pip { return }<br><br>            coordinator.animate(alongsideTransition: nil) { transitionContext in<br>                self.presentationState = .inline<br>                // Automatically, it will pause<br>                // Keep it playing!<br>                playerViewController.player?.play()<br>            }<br>        }<br>        <br>        // PiP<br>        <br>        public func playerViewController(<br>            _ playerViewController: AVPlayerViewController,<br>            failedToStartPictureInPictureWithError error: any Error<br>        ) {<br>            print(&quot;[MultimediaPlayer - PiPVieoPlayer.playerViewControllerFailedToStartPictureInPictureWithError]: Error = \(error)&quot;)<br>        }<br>        @MainActor public func playerViewControllerDidStartPictureInPicture(<br>            _ playerViewController: AVPlayerViewController<br>        ) {<br>            presentationState = .pip<br>        }<br>        @MainActor public func playerViewControllerDidStopPictureInPicture(<br>            _ playerViewController: AVPlayerViewController<br>        ) {<br>            // Always resets to inline after PiP mode ended<br>            presentationState = .inline<br>        }<br>    }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*CNHfFQn6STdcvMFrk4J0lQ.png" /></figure><h3>#3 — Configure for PiP &amp; background mode</h3><p>All we need to do is set 2 properties on the player view controller, configure the audio session, and enable background modes, then we get PiP mode for free! Please note, <strong>PiP mode cannot be tested in the simulator</strong>!</p><h4>Step 1 — Configure the audio session</h4><p>This is something <strong>any app should do that plays audio</strong>, so if you’re doing it properly, the only <em>extra step</em> for PiP is setting the properties. In case you don’t know what I’m on about, the audio session (or rather, <a href="https://developer.apple.com/documentation/avfoundation/configuring-your-app-for-media-playback">AVAudioSession from the AVKit/AVFoundation library) registers your use of audio</a> for the system to handle. For example, you can mute other apps to play your audio, play audio with the silent mode switch turned on, and the like. this is all controlled by the audio session. Look in the linked document for more information.</p><p>You just need to call setCategory on the shared instance, to .playback and then call setActive(true) to start using the audio session. Do this when you create the AVPlayerViewController:</p><pre>func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>    playerController.player = player<br>    playerController.delegate = context.coordinator<br>    <br>    // Set up the audio session for playback of movies<br>    do {<br>        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)<br>        try AVAudioSession.sharedInstance().setActive(true)<br>    } catch {<br>        print(&quot;[MyVideoPlayer]: Failed to set up audio session \(error)&quot;)<br>    }<br>    <br>    return playerController<br>}</pre><p>This has another side effect — allowing background audio as well!</p><h4>Step 2 — <a href="https://medium.com/@gokhanmutlu/implementing-picture-in-picture-pip-with-swiftui-ae1a0ae18939">Setting properties on the `AVPlayerViewController`</a></h4><pre>playerController.allowsPictureInPicturePlayback = true<br>playerController.canStartPictureInPictureAutomaticallyFromInline = true</pre><ul><li>allowsPictureInPicturePlayback → Like a master control</li><li>canStartPictureInPictureAutomaticallyFromInline → <em>A Boolean value that indicates whether Picture in Picture starts automatically when transitioning to the background when the view controller presents its content inline.</em> (Apple docs)</li></ul><h4>Allowing background mode</h4><p>It’s nearly set up — the player view controller <em>can</em> go into PiP mode, the audio session is OK, but unless our app is allowed ton play audio in the background (ie once our app is closed) it won’t work.</p><p>There are lots of types of background modes, but all you need to do is enable the audio one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*C3arspdVAiJKb7XrllB-zg.png" /><figcaption>Searching for background modes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*yerK6D71uwQ5OvwTUCwP9g.png" /><figcaption>Enable background mode for audio</figcaption></figure><p>PiP mode will now work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*bh7g2yI2mAyz1cIhGC9V1w.png" /></figure><h3>#4 — Add metadata to the Now Playing info center</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*fLxISwheeagCH5JP7x_q0Q.png" /></figure><blockquote>I think this is the hardest part as there’s so much documentation about it but hardly any awareness. As stated, WWDC videos &amp; documentation is linked as we go, so it’s definitely worth watching / reading from Apple &amp; the other sources if you want more information.</blockquote><p>Firstly, what even is the <em>now playing info center</em>? Simply <strong>data in the <em>music panel</em> of the control center</strong>. It was only <a href="https://medium.com/@quangtqag?source=post_page---byline--516243c2cdd1---------------------------------------">Quang Quoc Tran</a> who gave me the segue into the <em>now playing</em> realm, so thanks a lot! It is <a href="https://developer.apple.com/documentation/mediaplayer#Now-Playing-information"><strong>managed by the MediaPlayer</strong></a><strong> framework</strong>.</p><p><a href="https://medium.com/@quangtqag/background-audio-player-sync-control-center-516243c2cdd1">Background Audio Player Sync Control Center</a></p><p>Secondly, there is already some <strong>basic functionality in the now playing info center</strong>, such as the play/pause, seek, and current time / duration, and they update too if the AVPlayerViewController‘s rate changes. However ideally, we would have artwork and the video’s name &amp; creator rather than a blank square &amp; the app name.</p><p><a href="https://developer.apple.com/videos/play/wwdc2019/501/">To fix that, we <strong>set attributes on the player controller’s player’s current item</strong></a>. To help with this, I created a struct to represent these details and a helper that accepts them as a parameter and the AVPlayerItem.</p><pre>import Foundation<br>import MediaPlayer<br>import AVKit<br><br>struct NowPlayingMetadata: Sendable {<br>    let title: String<br>    let creator: String<br>    let artwork: UIImage<br>    <br>    init(title: String, creator: String, artwork: UIImage) {<br>        self.title = title<br>        self.creator = creator<br>        self.artwork = artwork<br>    }<br>    <br>    init(title: String, creator: String, artworkName: String, artworkExtension: String) {<br>        self.title = title<br>        self.creator = creator<br>        self.artwork = UIImage(contentsOfFile: artworkURL.path(percentEncoded: false))!<br>        self.artwork = UIImage(contentsOfFile: artworkURL)!<br>    }<br>}<br><br><br>struct NowPlayingHelper {<br>    private init() { }<br>    <br>    static func publishMetadata(_ metadata: NowPlayingMetadata, to playerItem: AVPlayerItem) {<br>        <br>    }<br>}</pre><p>All you do now is input the metadata to MyVideoPlayer and publish it into the player item which then automatically manages displaying it.</p><pre>struct MyVideoPlayer: UIViewControllerRepresentable {<br>    let metadata: NowPlayingMetadata<br>    <br>    func makeUIViewController(context: Context) -&gt; AVPlayerViewController {        <br>        // Publish the metadata to the player&#39;s current item<br>        if let item = player.currentItem {<br>            NowPlayingHelper.publishMetadata(metadata, to: item)<br>        } else {<br>            print(&quot;[MyVideoPlayer]: Cannot get the player&#39;s currentItem to publish the metadata to&quot;)<br>        }<br>        <br>        return playerController<br>    }</pre><pre>struct ContentView: View {<br>    let metadata = NowPlayingMetadata(title: &quot;Céline Dion - I&#39;m Alive (Official HD Video)&quot;, creator: &quot;Celine Dion&quot;, artworkName: &quot;movie&quot;, artworkExtension: &quot;webp&quot;)<br>    MyVideoPlayer(player: player, metadata: metadata, presentationMode: $presentationMode)<br>}</pre><p>So, how exactly do we publish the metadata fields in NowPlayingMetadata to the AVPlayerItem? We just have to set the player item’s externalMetadata property to a list of AVMutableMetadataItem that is created and given a</p><ul><li><strong>identifier</strong> ex. .commonIdentifierTitle/Creator/Artwork</li><li><strong>value</strong>, ex. “Celine Dion” or artwork image data</li><li><strong>dataType</strong> (only needed if the value is a file) ex. kCMMetadataBaseDataType_PNG indicating that the artwork data (in value) is a PNG image</li><li><strong>extendedLanguageTag</strong> always set to “und” for undefined. If it was set to a language, the metadata field would only appear if the device was set to that language.</li></ul><pre>struct NowPlayingHelper {<br>    private init() { }<br>    <br>    static func publishMetadata(_ metadata: NowPlayingMetadata, to playerItem: AVPlayerItem) {<br>        let creator = AVMutableMetadataItem()<br>        creator.identifier = .commonIdentifierCreator<br>        creator.value = metadata.creator as NSString<br>        creator.extendedLanguageTag = &quot;und&quot;<br>        <br>        let title = AVMutableMetadataItem()<br>        title.identifier = .commonIdentifierTitle<br>        title.value = metadata.title as NSString<br>        title.extendedLanguageTag = &quot;und&quot;<br>                <br>        var artwork: AVMutableMetadataItem?<br>        if let artworkData = metadata.artwork.pngData() {<br>            artwork = AVMutableMetadataItem()<br>            artwork!.identifier = .commonIdentifierArtwork<br>            artwork!.value = artworkData as NSData<br>            artwork!.dataType = kCMMetadataBaseDataType_PNG as String<br>            artwork!.extendedLanguageTag = &quot;und&quot;<br>        } else {<br>            print(&quot;[MultimediaPlayer: NowPlayingHelper.publishMetadata]: Cannot get the thumbnail&#39;s PNG data, so not adding the artwork to the now playing information&quot;)<br>        }<br>        <br>        playerItem.externalMetadata = [creator, title, artwork].compactMap(\.self)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*mYllG6vzqg5XnXr46FRxpw.gif" /></figure><h4>Background for Now Playing Information (if you’re interested)</h4><blockquote><em>In the </em><a href="https://developer.apple.com/documentation/mediaplayer#Now-Playing-information"><strong><em>MediaPlayer</em></strong></a><em> framework, there are classes such as </em><strong><em>MPRemoteCommandCenter</em></strong><em>, and </em><strong><em>MPNowPlayingInfoCenter</em></strong><em> that help us configure the buttons &amp; metadata in the now playing info center (the thing in the control center).</em></blockquote><blockquote><a href="https://developer.apple.com/videos/play/wwdc2019/501/"><em>From a WWDC 2019 video</em></a><em>, I learned that your app can publish data there if it is considered as a now playing app. For it to be a now playing app, it must add functionality to 1 or more buttons in the now playing center and provide metadata such as artwork, title, or description.</em></blockquote><blockquote><em>I also learned that </em><strong><em>for custom video players</em></strong><em> (ie. not </em><em>AVPlayerViewController) you should use the remote command center to add a target action to the pause, play, stop, skip, etc. buttons as well as seek action. </em><a href="https://developer.apple.com/videos/play/wwdc2019/501/"><em>You can set keys</em></a><em> like </em><a href="https://developer.apple.com/documentation/mediaplayer/mpmediaitempropertyartwork"><em>MPMediaItemPropertyArtwork</em></a><em> or </em><a href="https://developer.apple.com/documentation/mediaplayer/mpmediaitempropertytitle"><em>MPMediaItemPropertyTitle</em></a><em> in the default instance of the now playing info centre’s </em><em>nowPlayingInfo dictionary.</em></blockquote><blockquote><em>When the instance property </em><em>updatesNowPlayingInfoCenter on </em><em>AVPlayerViewController is set to true, a player view controller manages its own now playing info so I cannot add in my own metadata or alter the now playing info dictionary at all — well doing so has no effect on the now playing info center.</em></blockquote><blockquote><em>Why haven’t I shown you code? Because we’re using the </em><em>AVPlayerViewController, so cannot add any metadata like this. It’s just here for a bit of background and to spread awareness about this underrated API!</em></blockquote><blockquote><a href="https://developer.apple.com/videos/play/wwdc2022/110338/"><em>From a WWDC 2022 video</em></a><em>, I learned that there is another way to access the now playing information/commands aside from the manual way as described above. In the more modern, automatic way (available in iOS 16+), there is an </em><strong><em>MPNowPlayingSession created from 1+ </em></strong><strong><em>AVPlayers</em></strong><em>.</em></blockquote><blockquote><em>When its </em><em>automaticallyPublishesNowPlayingInfo property is set to </em><strong><em>false</em></strong><em>, we must update the keys &amp; values in its </em><em>nowPlayingInfoCenter.nowPlayingInfo dictionary ourself. When true, we have no control over the dictionary as the keys/values are set automatically. And as for the remote actions, they are always automatic, coming from the </em><em>AVPlayer. Dynamic playback-related information like the video’s playback rate, elapsed time &amp; duration, are updated automatically but we have to assign the static metadata (like title, artwork, and creator) ourselves.</em></blockquote><blockquote><em>As described above, we do this by creating an array of </em><em>AVMutableMetadataItem instances with the </em><strong><em>identifier</em></strong><em> set to identify the type of metadata (like </em><em>.commonIdentifierCreator, or </em><em>.commonIdentifierTitle, or </em><em>.commonIdentifierArtwork), </em><strong><em>value</em></strong><em> like an </em><em>NSString or </em><em>NSData for the artwork, optionally, a </em><strong><em>dataType for the artwork</em></strong><em> (set to a constant like </em><em>kCMMetadataBaseDataType_PNG) and lastly, a </em><strong><em>language (</em></strong><em>extendedLanguageTag) which should always be set to undefined, </em><em>&quot;und&quot;. </em><strong><em>Assign this array to an AVPlayer’s </em></strong><strong><em>currentItem?.externalMetadata</em></strong><em>. Then, the now playing session will have this data to use and put in the UI!</em></blockquote><blockquote><em>Let me repeat that an </em><em>AVPlayerViewController manages its own now playing session, and we can’t control any dictionaries, or anything like that. We must also </em><strong><em>not create any </em></strong><strong><em>MPNowPlayingSession</em></strong><em> for it either — it has its own; </em>you only need to worry about setting up an automatic MPNowPlayingSession or manually maintaining keys in the MPNowPlayingInfoCenter dictionary <strong>if you are creating your own video player</strong>.</blockquote><h3>#5 — Making it work with audio as well</h3><p>I also had no idea about this until I read <a href="https://medium.com/@samwise23/playing-audio-with-avplayer-in-swift-b3ce82fbeb6d">Sam’s article here on Medium</a> about it:</p><p><a href="https://medium.com/@samwise23/playing-audio-with-avplayer-in-swift-b3ce82fbeb6d">Playing Audio with AVPlayer in Swift</a></p><h4><a href="https://stackoverflow.com/questions/3282866/avplayer-vs-avaudioplayer">AVPlayer vs AVAudioPlayer</a></h4><p>As you have seen, AVPlayer is a very good API we can use to play video, but did you know it can also play audio as well? It’s capable of networking as well, and streaming media from the network to play, and it can even handle HLS streams (m3u8). You can use it with MPNowPlayingSession to automatically manage the now playing information, and lastly, (<a href="https://developer.apple.com/documentation/avfoundation/observing-playback-state-in-swiftui">when </a><a href="https://developer.apple.com/documentation/avfoundation/observing-playback-state-in-swiftui">AVPlayer.isObservationEnabled = true) it acts as a view-model</a> publishing UI updates when its fields like timeControlStatus change. This means you don’t need to do any KVO (key-value observation).</p><p><a href="https://developer.apple.com/documentation/avfoundation/audio-playback-recording-and-processing">AVAudioPlayer does none of this</a>, it just simply inputs an audio URL to play, and plays it. This means it comes with far less overhead, although it’s much harder for you to implement more complex audio players with it. I use this when playing simple sound effects, when I don’t really care about keeping a UI &amp; now playing information updated.</p><h4>AVPlayerViewController &amp; Audio playing</h4><p>What does an AVPlayerViewController look like playing audio? The<strong> controls are the same, but there is no video</strong>. There is a placeholder graphic instead.</p><p>Here is my new ContentView used to take a look at this. I just added another MyVideoPlayer instance with an AVPlayer created from my audio.mp3 file</p><pre>import SwiftUI<br>import AVKit<br><br>struct ContentView: View {<br>    @State private var audioPlayer: AVPlayer?<br>    @State private var audioPresentationMode = VideoPlayerPresentationMode.inline<br>    <br>    var body: some View {<br>        VStack {<br>            if let audioPlayer {<br>                MyVideoPlayer(player: audioPlayer, metadata: metadata, presentationMode: $presentationMode)<br>                    .aspectRatio(16/9, contentMode: .fit)<br>            } else {<br>                Text(&quot;Cannot load video&quot;)<br>            }<br>        }<br>        .onAppear {<br>            let audioURL = Bundle.main.url(/service/forresource: &quot;audio&quot;, withExtension: &quot;mp3&quot;)!<br>            audioPlayer = AVPlayer(url: url)<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*psQMAIBoJeBnwdk7FrlFiw.png" /></figure><h4>Telling if audio or video &amp; refactoring MyVideoPlayer → MyMultimediaPlayer</h4><p>Let’s refactor the MyVideoPlayer to be called MyMultimediaPlayer since it can indeed play audio as well! I won’t show the code for this.</p><p>Let’s add another enum &amp; initialize it in MyVideoPlayer that just tracks if the AVPlayer is containing video or audio.</p><pre>enum MultimediaType {<br>    case audio, video<br>}<br><br>struct MyMultimediaPlayer: UIViewControllerRepresentable {<br>    let type: MultimediaType<br>}</pre><pre>struct ContentView: View {<br>    MyMultimediaPlayer(player: player, metadata: metadata, type: .video, presentationMode: $presentationMode)<br>    MyMultimediaPlayer(player: audioPlayer, metadata: metadata, type: .audio, presentationMode: $presentationMode)<br>}</pre><p>Lastly, PiP doesn’t make that much sense in audio mode; you can disable it if you want by setting playerController.allowsPictureInPicturePlayback = type == .video in the <em>MyMultimediaPlayer.makeUIViewController</em>.</p><h4>Putting the audio thumbnail above the placeholder</h4><p>Rather than having this boring placeholder, let’s put the audio’s thumbnail (or <strong>artwork, from the </strong><strong>NowPlayingMetadata) underneath the controls</strong> and in front of the placeholder. To do this, AVPlayerViewController provides a contentOverlayView which is just this. I will do this in a separate function called only if type == .audio.</p><p>Of course we are in UIKit mode now, so the first thing you have to do is create a UIImageView with the UIImage from metadata.artwork. Set the contentMode to whatever you want — I like a mix of .scaleAspectFill with clipToBounds = true to cut off the edges. Add constraints to constrain it inside its parent AVPlayerViewController.view and it as a subview to the player view controller’s contentOverlayView.</p><blockquote>Note that <em>contentOverlayView</em> is never nil here.</blockquote><pre>struct MyMultimediaPlayer: UIViewControllerRepresentable {<br>    func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>        if type == .audio {<br>            addThumbnail()<br>        }<br>    }<br>    <br>    func addThumbnail() {<br>        // Create an image view<br>        let imageView = UIImageView(image: metadata.artwork)<br>        // Set the scale mode so it fills up the entire view controller<br>        imageView.contentMode = .scaleAspectFill<br>        // Cut off the edges that may be overhanging<br>        imageView.clipsToBounds = true<br>        <br>        // Add thre image inside the overlay view<br>        playerController.contentOverlayView?.addSubview(imageView)<br>        <br>        // Add constraints for the width/height and x/y<br>        imageView.translatesAutoresizingMaskIntoConstraints = false<br>        imageView.heightAnchor.constraint(equalTo: imageView.superview!.heightAnchor).isActive = true<br>        imageView.widthAnchor.constraint(equalTo: imageView.superview!.widthAnchor).isActive = true<br>        imageView.bottomAnchor.constraint(equalTo: imageView.superview!.bottomAnchor).isActive = true<br>        imageView.leadingAnchor.constraint(equalTo: imageView.superview!.leadingAnchor).isActive = true<br>        imageView.trailingAnchor.constraint(equalTo: imageView.superview!.trailingAnchor).isActive = true<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*WmqTVU0OknuXkTZram_u1A.gif" /></figure><p>And there we have it! It’s complete! Thanks for following — please ask if you have questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b0b67da0db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liquid glass text effect in SwiftUI for macOS & iOS]]></title>
            <link>https://medium.com/@danielcrompton5/liquid-glass-text-effect-in-swiftui-for-macos-ios-7468ced04e35?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7468ced04e35</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[liquid-glass]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 22:24:34 GMT</pubDate>
            <atom:updated>2025-09-06T22:24:34.949Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to recreate the liquid glass text from Apple’s lock-screen screenshots, in a fully customizable way, in the fonts &amp; glass</h4><p>The screenshot that inspired me was the following image; I found a way to add glass effects to text in SwiftUI so you can use it in your views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*RVp4_C6GfNuIAz4TEpM8CQ.png" /></figure><h3>Use my package:</h3><p>To save the work of following this guide you can use my Github package that is identical to this tutorial: <a href="https://github.com/DanielCrompton123/LiquidGlassText/tree/main"><strong>https://github.com/DanielCrompton123/LiquidGlassText/tree/main</strong></a></p><h3>My approach:</h3><ol><li>First, I will create a package that can easily be imported into other projects</li><li>Next I will create a helper that takes in an attributed string and return a SwiftUI Path that we can apply the .glassEffect modifier to.</li><li>I will create a LiquidGlassText that inputs the attributed string, and applies the liquid glass to the string input’s path.</li><li>Lastly, I will bridge changes to macOS and add other OS support such as visionOS and tvOS</li></ol><h4>My version:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*vknJ0SSMioxg7nOuZ8Ffbw.png" /></figure><h3>Step 1 — Create the package</h3><p>In Xcode, go to File &gt; New &gt; Package, and follow Xcode’s stages to create the package. If you’d like, you can write the helper &amp; liquid glass text views in an existing project but I would recommend using a package and importing.</p><h3>Step 2 — Create the text helper</h3><p>How liquid glass works, is by taking as view and applying the .glassEffect(glass, shape) modifier passing in the type of glass (regular, clear, and identity, although you can add a tint and make them interactive) and the shape to fill the glass in.</p><pre>#Preview {<br>    Text(&quot;Hello world&quot;)<br>        .padding()<br>        .padding()<br>        .glassEffect(.regular, in: .ellipse)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*ZMcnzzoX_wC4zhyI5U_FfA.png" /><figcaption>The view produced by the code above</figcaption></figure><p><strong>Liquid glass, as of iOS 26 beta, can only fill shapes</strong>, and because text is made of shapes, the approach I took was <strong>converting the text to a bunch of paths</strong>, and using the .glassEffect modifier to fill it with liquid glass.</p><p>Doing this requires use of the core foundation types and the <strong>CoreText framework</strong>. So to save time, I used AI to help me implement this helper.</p><pre>import SwiftUI<br>import CoreText<br><br><br>struct TextHelper {<br>    private init() { }<br>    <br>    static func path(for string: NSAttributedString) -&gt; Path {<br>        let line = CTLineCreateWithAttributedString(string)<br>        let runs = CTLineGetGlyphRuns(line) as NSArray<br>        <br>        let outputPath = CGMutablePath()<br>        <br>        for i in 0..&lt;CFArrayGetCount(runs) {<br>            let run = unsafeBitCast(CFArrayGetValueAtIndex(runs, i), to: CTRun.self)<br>            let attributes = CTRunGetAttributes(run) as NSDictionary<br>            // This conditional downcast will always succeed if the key is present, as CTFont is toll-free bridged.<br>            // The as? avoids a crash if the attribute is missing; the warning can be ignored.<br>            let key = kCTFontAttributeName as NSAttributedString.Key<br>            guard let anyCTFont = attributes[key] else {<br>                print(&quot;[LiquidGlassText] Missing font attribute in run attributes: \(attributes)&quot;)<br>                continue<br>            }<br>            let ctFont = anyCTFont as! CTFont<br>            <br>            let glyphCount = CTRunGetGlyphCount(run)<br>            var glyphs = [CGGlyph](repeating: 0, count: glyphCount)<br>            var positions = [CGPoint](repeating: .zero, count: glyphCount)<br>            <br>            CTRunGetGlyphs(run, CFRangeMake(0, 0), &amp;glyphs)<br>            CTRunGetPositions(run, CFRangeMake(0, 0), &amp;positions)<br>            <br>            for j in 0..&lt;glyphCount {<br>                if let glyphPath = CTFontCreatePathForGlyph(ctFont, glyphs[j], nil) {<br>                    let position = positions[j]<br>                    let transform = CGAffineTransform(translationX: position.x, y: position.y)<br>                    outputPath.addPath(glyphPath, transform: transform)<br>                }<br>            }<br>        }<br>        <br>        let swiftUIPath = Path(outputPath)<br>        let bounds = swiftUIPath.boundingRect<br>        // Flip vertically within the bounds<br>        let flipped = swiftUIPath.applying(CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -bounds.height))<br>        return flipped<br>    }<br>}</pre><p>And viewing a preview:</p><pre>// MARK: Text helper text<br>#Preview(&quot;TextHelper test&quot;) {<br>    TextHelper.path(for: NSAttributedString(string: &quot;16:49&quot;, attributes: [.font: UIFont.boldSystemFont(ofSize: 70)]))<br>        .fill(.black)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*5pFzC1uPMaFWgM179dqM8w.png" /><figcaption>Preview generated by the above view</figcaption></figure><p>As you can see, the text is displaying although it is a path instead of Text. It is also pushed to the top left corner of the view because Path is a push-out view, so takes the entire screen, although the text shape points aren’t adjusted to be in the center. This isn’t an issue we are concerned about as we will fix it later.</p><h3>Step 3 — Create the LiquidGlassText view</h3><p>This serves as a handy wrapper that can input an NSAttributedString, String, as well as font properties to use to display the text, fix the size of the view (as demonstrated in the previous image) and apply the liquid glass.</p><pre>import SwiftUI<br><br>public struct LiquidGlassText: View {<br>    <br>    //MARK: - Properties<br>    private let string: NSAttributedString<br>    private let glass: Glass<br>    <br>    //MARK: - Initializers<br>    public init(_ string: NSAttributedString, glass: Glass = .regular) {<br>        self.string = string<br>        self.glass = glass<br>    }<br>    <br>    public init(_ string: String, glass: Glass = .regular) {<br>        self.string = NSAttributedString(string: string)<br>        self.glass = glass<br>    }<br>    <br>    public init(_ string: String, glass: Glass = .regular, fontName: String, size: CGFloat = UIFont.systemFontSize) {<br>        let attrs: [NSAttributedString.Key: Any] = [<br>            .font: UIFont(name: fontName, size: size) as Any<br>        ]<br>        self.string = NSAttributedString(string: string, attributes: attrs)<br>        self.glass = glass<br>    }<br>    <br>    // MARK: - Body<br>    public var body: some View {<br>        let path = TextHelper.path(for: string)<br>        <br>        Color.clear<br>            .glassEffect(glass, in: path)<br>            .frame(width: path.boundingRect.width, height: path.boundingRect.height)<br>    }<br>    <br>}</pre><p>This view:</p><ul><li>firstly stores the NSAttributedString that is used to create paths, as well as the type of glass to use.</li><li>has 3 different initializers, one to input the NSAttributedString and glass type, another to input a String and glass type (where the default NSAttributedString is created from the String) and a third to input the string, custom font name, size, and type of glass</li><li>declares a body that uses the text helper to create paths from the text. It displays a clear color (that by default is a push-out view) so we have something to apply the glassEffect modifier to. Then we apply that modifier filling the text path with the stored glass, and lastly, setting the frame of the view to the bounds of the text path (this fixes the font alignment issue where it sticks to the top-left corner)</li></ul><h3>Step 4 — Bridging to other OSs</h3><p>While this uses the UIFont and other UIKit types for iOS, macOS uses NS types so the code cannot build for macOS. We need to declare and use a typealias for all the UIKit types we have, that are conditionally set depending on macOS or iOS. Other OSs like tvOS and visionOS use UIKit too so we only need to redefine some behavior for macOS. watchOS is not exposed to UIKit so the effects cannot be made there.</p><p>I will create a font helper that is responsible for managing these type-aliases and creating fonts for different platforms.</p><pre>import SwiftUI<br><br>#if os(iOS) || os(visionOS) || os(tvOS)<br>    public typealias UXFont = UIFont<br>    public typealias UXDesign = UIFontDescriptor.SystemDesign<br>    public typealias UXWeight = UIFont.Weight<br>    public typealias UXWidth = UIFont.Width<br>    public typealias UXDescriptor = UIFontDescriptor<br>#elseif os(macOS)<br>    public typealias UXFont = NSFont<br>    public typealias UXDesign = NSFontDescriptor.SystemDesign<br>    public typealias UXWeight = NSFont.Weight<br>    public typealias UXWidth = NSFont.Width<br>    public typealias UXDescriptor = NSFontDescriptor<br>#endif<br><br>struct FontHelper {<br>    <br>    <br>    private init() { }<br>    <br>    static func font(forSize size: CGFloat, weight: UXWeight, width: UXWidth, design: UXDesign) -&gt; UXFont {<br>        <br>        let baseDescriptor = UXFont.systemFont(ofSize: size).fontDescriptor<br>        <br>        let descriptorWithDesign = baseDescriptor.withDesign(design) ?? baseDescriptor<br>        let descriptor = descriptorWithDesign.addingAttributes([<br>            UXDescriptor.AttributeName.traits: [<br>                UXDescriptor.TraitKey.weight: weight,<br>                UXDescriptor.TraitKey.width: width<br>            ]<br>        ])<br>        <br>        return UXFont(descriptor: descriptor, size: size) ?? UXFont.systemFont(ofSize: size)<br>    }<br>    <br>    static func font(named name: String, size: CGFloat) -&gt; UXFont {<br>        UXFont(name: name, size: size) ?? .systemFont(ofSize: size)<br>    }<br>}</pre><p>Now we can adjust the UIKit types to use UX-types (like UXFont, instead of UIFont or NSFont).</p><h3>Full code:</h3><h4>FontHelper.swift</h4><pre>import SwiftUI<br><br>#if os(iOS) || os(visionOS) || os(tvOS)<br>    public typealias UXFont = UIFont<br>    public typealias UXDesign = UIFontDescriptor.SystemDesign<br>    public typealias UXWeight = UIFont.Weight<br>    public typealias UXWidth = UIFont.Width<br>    public typealias UXDescriptor = UIFontDescriptor<br>#elseif os(macOS)<br>    public typealias UXFont = NSFont<br>    public typealias UXDesign = NSFontDescriptor.SystemDesign<br>    public typealias UXWeight = NSFont.Weight<br>    public typealias UXWidth = NSFont.Width<br>    public typealias UXDescriptor = NSFontDescriptor<br>#endif<br><br>struct FontHelper {<br>    <br>    <br>    private init() { }<br>    <br>    static func font(forSize size: CGFloat, weight: UXWeight, width: UXWidth, design: UXDesign) -&gt; UXFont {<br>        <br>        let baseDescriptor = UXFont.systemFont(ofSize: size).fontDescriptor<br>        <br>        let descriptorWithDesign = baseDescriptor.withDesign(design) ?? baseDescriptor<br>        let descriptor = descriptorWithDesign.addingAttributes([<br>            UXDescriptor.AttributeName.traits: [<br>                UXDescriptor.TraitKey.weight: weight,<br>                UXDescriptor.TraitKey.width: width<br>            ]<br>        ])<br>        <br>        return UXFont(descriptor: descriptor, size: size) ?? UXFont.systemFont(ofSize: size)<br>    }<br>    <br>    static func font(named name: String, size: CGFloat) -&gt; UXFont {<br>        UXFont(name: name, size: size) ?? .systemFont(ofSize: size)<br>    }<br>}</pre><h4>LiquidGlassText.swift</h4><pre>import SwiftUI<br><br>public struct LiquidGlassText: View {<br>    <br>    //MARK: - Properties<br>    private let string: NSAttributedString<br>    private let glass: Glass<br>    <br>    //MARK: - Initializers<br>    public init(_ string: NSAttributedString, glass: Glass = .regular) {<br>        self.string = string<br>        self.glass = glass<br>    }<br>    <br>    public init(_ string: String, glass: Glass = .regular) {<br>        self.string = NSAttributedString(string: string)<br>        self.glass = glass<br>    }<br>    <br>    public init(<br>        _ string: String,<br>        glass: Glass = .regular,<br>        <br>        size: CGFloat = UXFont.systemFontSize,<br>        weight: UXWeight = .regular,<br>        width: UXWidth = .standard,<br>        design: UXDesign = .default<br>    ) {<br>        let attrs: [NSAttributedString.Key: Any] = [<br>            .font: FontHelper.font(forSize: size, weight: weight, width: width, design: design)<br>        ]<br>        self.string = NSAttributedString(string: string, attributes: attrs)<br>        self.glass = glass<br>    }<br>    <br>    public init(_ string: String, glass: Glass = .regular, fontName: String, size: CGFloat = UXFont.systemFontSize) {<br>        let attrs: [NSAttributedString.Key: Any] = [<br>            .font: FontHelper.font(named: fontName, size: size) as Any<br>        ]<br>        self.string = NSAttributedString(string: string, attributes: attrs)<br>        self.glass = glass<br>    }<br>    <br>    // MARK: - Body<br>    public var body: some View {<br>        let path = TextHelper.path(for: string)<br>        <br>        Color.clear<br>            .glassEffect(glass, in: path)<br>            .frame(width: path.boundingRect.width, height: path.boundingRect.height)<br>    }<br>    <br>}</pre><h4>TextHelper.swift</h4><pre>struct TextHelper {<br>    private init() { }<br>    <br>    static func path(for string: NSAttributedString) -&gt; Path {<br>        let line = CTLineCreateWithAttributedString(string)<br>        let runs = CTLineGetGlyphRuns(line) as NSArray<br>        <br>        let outputPath = CGMutablePath()<br>        <br>        for i in 0..&lt;CFArrayGetCount(runs) {<br>            let run = unsafeBitCast(CFArrayGetValueAtIndex(runs, i), to: CTRun.self)<br>            let attributes = CTRunGetAttributes(run) as NSDictionary<br>            // This conditional downcast will always succeed if the key is present, as CTFont is toll-free bridged.<br>            // The as? avoids a crash if the attribute is missing; the warning can be ignored.<br>            let key = kCTFontAttributeName as NSAttributedString.Key<br>            guard let anyCTFont = attributes[key] else {<br>                print(&quot;[LiquidGlassText] Missing font attribute in run attributes: \(attributes)&quot;)<br>                continue<br>            }<br>            let ctFont = anyCTFont as! CTFont<br>            <br>            let glyphCount = CTRunGetGlyphCount(run)<br>            var glyphs = [CGGlyph](repeating: 0, count: glyphCount)<br>            var positions = [CGPoint](repeating: .zero, count: glyphCount)<br>            <br>            CTRunGetGlyphs(run, CFRangeMake(0, 0), &amp;glyphs)<br>            CTRunGetPositions(run, CFRangeMake(0, 0), &amp;positions)<br>            <br>            for j in 0..&lt;glyphCount {<br>                if let glyphPath = CTFontCreatePathForGlyph(ctFont, glyphs[j], nil) {<br>                    let position = positions[j]<br>                    let transform = CGAffineTransform(translationX: position.x, y: position.y)<br>                    outputPath.addPath(glyphPath, transform: transform)<br>                }<br>            }<br>        }<br>        <br>        let swiftUIPath = Path(outputPath)<br>        let bounds = swiftUIPath.boundingRect<br>        // Flip vertically within the bounds<br>        let flipped = swiftUIPath.applying(CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -bounds.height))<br>        return flipped<br>    }<br>}<br><br>// MARK: Text helper text<br>#Preview(&quot;TextHelper test&quot;) {<br>    TextHelper.path(for: NSAttributedString(string: &quot;16:49&quot;, attributes: [.font: UXFont.boldSystemFont(ofSize: 70)]))<br>        .fill(.black)<br>}</pre><h3>Thanks for reading!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7468ced04e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Slider-button in SwiftUI]]></title>
            <link>https://medium.com/@danielcrompton5/building-a-slider-button-in-swiftui-c141624fb3c0?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c141624fb3c0</guid>
            <category><![CDATA[button]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[slider]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 16:13:11 GMT</pubDate>
            <atom:updated>2025-04-26T16:14:30.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>I will show you how to build this fun UI component enabling users to swipe to complete an action.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*dk-Qw_RBxmeDeZ5LQxgkfw.gif" /><figcaption>Demo of what we will make</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRJIaa8Zi1tuiV1JeGGOoQ.png" /></figure><h3>Why?</h3><p>I like to use this slider to <strong>obfuscate a destructive action</strong> that can be easily performed by accident. It is an alternative to using an alert or conformation dialogue, for example, when deleting content.</p><h3>Contents</h3><ul><li>Set up a basic view</li><li>Add the drag gestures to it</li><li>Detect progress &amp; completion</li><li>Make it latch on/off, and bounce back</li><li>Add background &amp; foreground elements</li></ul><h3>Setting up view</h3><h4>Creating the basis</h4><p>To begin with, let’s create the basis of the slider-button:</p><pre>struct TutorialSliderButton: View {<br>    var knobPadding: CGFloat = 8<br>    <br>    var body: some View {<br>        ZStack(alignment: .leading) {<br>            // TRACK<br>            Capsule()<br>                .fill(.tint.quaternary)<br>            // KNOB<br>            Circle()<br>                .fill(.tint)<br>                .padding(knobPadding)<br>        }<br>        .frame(height: 60)<br>    }<br>}<br><br>#Preview {<br>    TutorialSliderButton()<br>}</pre><p>In this code:</p><ul><li>I overlay a circular knob on top of a capsule track, using the ZStack, with an alignment of leading to make the knob align to the left-hand-side of the track</li><li>By <strong><em>track</em></strong> I mean the capsule layered at the bottom — where the knob will slide in</li><li>I use the <em>.tint</em> shape style for the knob, and the <em>.tint.quaternary</em> to get the quaternary version. <strong>Remember</strong> that shape styles have a primary, secondary, tertiary, quaternary, and a quinary version where the opacity &amp; prominence decreases each level — in this case I want a relatively faint tint for the track.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*2t0LM_IWEPk27T3AEO-WSw.png" /><figcaption>The slider button created in the code above</figcaption></figure><blockquote>Note: if the <em>.tint</em> modifier is used to change the tint color, this affects the track &amp; knob, or if the AccentColor asset is changed too. <strong>For example</strong>:</blockquote><pre>#Preview {<br>    TutorialSliderButton()<br>        .tint(.red)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*A-9mEG1ST7ogFE5J4oknow.png" /><figcaption>With a red tint</figcaption></figure><h3>Creating the drag gesture</h3><h4>How to use gestures</h4><p>Firstly, <strong>pick a type of gesture you want to use</strong>. Simple ones like tap gesture &amp; long-press gesture have modifiers, like <em>onTapGesture</em> and <em>onLongPressGesture</em>, however complex ones like drag, magnification, rotation etc. gestures do not.</p><p>To use those, <strong>create an instance of them</strong> (e.g. <em>DragGesture()</em>) and use the <em>onChanged</em> and <em>onEnded</em> modifiers to respond to changes (like the finger dragging), and the gesture’s end (like when the finger is released after dragging) respectively.</p><p>In the <em>onChanged</em> and <em>onEnded</em> modifiers, you have access to the <strong>gesture’s <em>value</em></strong>, which contains data relevant to the specific gesture — in the drag gesture, we have <em>translation</em> which is the offset dragged by the user. You can then use this to make view updates, for example, updating a property to offset a view.</p><p>Lastly, to actually <strong>apply the gesture</strong> to a view, you use the <em>.gesture</em> modifier but the confusion comes for some, when <strong>creating</strong> the gesture. Here is one option, where the gesture is created directly inside the method:</p><pre>.gesture(<br>    GESTURE()<br>        .onChanged({ _ in<br>            // do something<br>        })<br>        .onEnded({ _ in<br>            // do something<br>        })<br>    , isEnabled: BOOLEANPROPERTY)</pre><p>As you can see, this is not as readable, and includes logic inside the view code. A more readable version I <strong>personally prefer</strong> is as follows, where the gesture is in its own property, <strong>not inside the view</strong>:</p><pre>TutorialSliderButton: View {<br>    var body: some View {<br>        VIEW<br>            .gesture(gesture, isEnabled: BOOLEANPROPERTY)<br>    }<br>    <br>    <br>    private var gesture: some Gesture {<br>        GESTURE()<br>            .onChanged { value in<br>                ...<br>            }<br>            .onEnded { value in<br>                ...<br>            }<br>    }<br>}</pre><p>Enough tell, now I will show:</p><h4>Using DragGesture in the slider</h4><pre>struct TutorialSliderButton: View {<br>    var knobPadding: CGFloat = 8<br>    <br>    //MARK: - View properties<br>    @State private var knobXOffset: CGFloat = 0<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        ZStack(alignment: .leading) {<br>            // TRACK<br>            Capsule()<br>                .fill(.tint.quaternary)<br>            // KNOB<br>            Circle()<br>                ...<br>                .offset(x: knobXOffset) // Set this BEFORE the gesture<br>                .gesture(dragGesture)<br>        }<br>        .frame(height: 60)<br>    }<br>    <br>    <br>    private var dragGesture: some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                knobXOffset = value.translation.width<br>            }<br>    }<br>}</pre><p>In this code:</p><ul><li>I have <strong>truncated the knob’s fill/padding modifiers with an ellipsis (…)</strong> — these <strong>have not changed</strong>, so it just saves space.</li><li>I create a <em>knobXOffset</em> property to store the x-offset of the knob relative to its original X position. This is updated when I drag</li><li>I create a property called <em>dragGestur</em>e, of type <em>some Gesture</em>, and add the <em>onChanged</em> modifier, in which I read the <em>translation</em> (i.e. the drag offset) and set it to the knob’s offset</li></ul><blockquote><strong>Note</strong>: If you have the offset modifier <strong>after</strong> the gesture, it will oscillate left/right — this is an undesired effect, so just make sure to put the offset modifier <strong>before</strong> gesture</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*D7dMRfscQEu6LJNd9K0P2Q.gif" /><figcaption>The knob with the drag gesture added</figcaption></figure><p>This can look <strong>glitchy</strong> as the knob resets to its original position on the second drag, however, don’t worry — we still have some work to do!</p><h4>Limiting the knob’s offset</h4><p>At the moment, the knob is free to have any X offset and slide outside of the track — to fix this, we just need to make sure the <strong>maximum offset is the right-hand side of the track, </strong>minus the knob’s width.</p><blockquote>Note: We could add logic to set a minimum offset, however I will not worry about this, as later, if dragged left, the knob will bounce back to its original position.</blockquote><p>The following diagram explains how we can calculate the knob’s maximum offset: <strong>track width - knob width:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSghJWVM7GP1Ae6PkQR46A.png" /><figcaption>How to calculate maximum X offset</figcaption></figure><p>We need to get the <strong>track width</strong> and the <strong>knob width:</strong></p><ul><li>For the track width, I will embed the whole view into a <em>GeometryReader</em>, limit its height, and get the size</li><li>for the knob width, I will use the <em>onGeometryChange</em> modifier — this is called whenever the <em>geometry</em> changes, <strong><em>geometry</em> relating to size &amp; position</strong>. Here is the anatomy of this modifier:</li></ul><pre>VIEW<br>    .onGeometryChange(for: (*A) ) { GeometryProxy in<br>        (*B)<br>    } action: { newValue in<br>        (*C)<br>    }</pre><p>Notes:</p><ul><li><strong>*A</strong>: This is a data type that we want to get from the geometry proxy</li><li><strong>*B</strong>: This function takes in the geometry proxy (exactly the same as what a <em>GeometryReader</em> gives) and returns a value from it. For example, to access the modified view’s size, we could access <em>GeometryProxy.size</em></li><li><strong>*C</strong>: This function takes in the value returned by *B. I.e. if *B returned <em>GeometryProxy.size</em>, this will be the value of <em>newValue</em> — we can then operate on it, for example, save it to a state variable like <em>knobWidth</em>. Also, *A will be <em>CGSize.self </em>as *B returns a <em>CGSize</em>. The <em>.self</em> part accesses the <em>CGSize</em> type <em>as a value</em>.</li></ul><p>Here is the full code (getting the track / knob size):</p><pre>struct TutorialSliderButton: View {<br>    var knobPadding: CGFloat = 8<br>    <br>    //MARK: - View properties<br>    @State private var knobXOffset: CGFloat = 0<br>    @State private var knobWidth: CGFloat = 0<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK<br>                Capsule()<br>                    .fill(.tint.quaternary)<br>                // KNOB<br>                Circle()<br>                    ...<br>                    .onGeometryChange(for: CGSize.self, of: { proxy in<br>                        proxy.size // get the modified view&#39;s size<br>                    }, action: { size in<br>                        self.knobWidth = size.width<br>                        print(&quot;Knob size = \(size)&quot;)<br>                    })<br>                    .offset(x: knobXOffset) // Set this BEFORE the gesture<br>                    .gesture(dragGesture)<br>            }<br>        }<br>        .frame(height: 60)<br>        .frame(maxWidth: .infinity)<br>    }<br>    <br>    <br>    private var dragGesture: some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                knobXOffset = value.translation.width<br>            }<br>    }<br>}</pre><blockquote><strong>Note</strong>: In the console I see printed: “Knob size = (60.0, 60.0)”</blockquote><p>Now we have access to those, let’s use them to calculate the maximum X offset and limit the knob’s offset to it:</p><blockquote><strong>Note</strong>: Not all code is shown here — this avoids a lot of repetition</blockquote><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK<br>                Capsule()<br>                    .fill(.tint.quaternary)<br>                // KNOB<br>                Circle()<br>                    ...<br>                    .gesture(dragGesture(with: geom))<br>            }<br>        }<br>        ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                // When dragged, set the X offset, but limit to the end of the slider:<br>                // - Get the maximum offset<br>                //   - Distance from slider&#39;s MIN X to (Slider&#39;s MAX X - knob width)<br>                // - Set the offset to min( offset , maximum offset )<br>                let geomFrame = geomProxy.frame(in: .local)<br>                let maxXOffset = geomFrame.minX.distance(to: geomFrame.maxX - knobWidth)<br>                knobXOffset = min(value.translation.width, maxXOffset)<br>            }<br>    }<br>}</pre><p>In this code:</p><ul><li>I firstly made the <em>dragGesture</em> into a function (from a computed value) because it needs to take in the track’s width in order to calculate the maximum X offset</li><li>I get the geometry frame (also the track frame) with <em>geomProxy.frame(in: .local)</em></li><li>I then calculate the maximum X offset, see the illustration above for the explanation</li></ul><h3>Detecting progress &amp; completion</h3><p>Firstly, let’s add 3 more properties to the slider-button:</p><ol><li><strong><em>onComplete: () -&gt; ()</em></strong><em> </em>— this will be called once the knob has been slid to the right-hand-side of the track — it mimics the action of a button.</li><li><strong><em>onDrag: (Double) -&gt; ()</em></strong><em> </em>— this will be called when the user drags the knob, and will accept the percentage complete, for example, 0.5 if the knob is dragged half-way towards the end, or 1 if all the way to the end, and 0 if at the start.</li><li><strong><em>latchesOn: Bool</em></strong> — if true, the knob stays dragged at the right-hand side of the track, once fully slid, meaning the action can only happen once. If false, the knob bounces back to its original position once slid fully right. Set this to false if you want the user to be able to perform the action multiple times.</li></ol><pre>struct TutorialSliderButton: View {<br>    var knobPadding: CGFloat = 8<br>    var onComplete: () -&gt; () = { }<br>    var onDrag: (Double) -&gt; () = { _ in }<br>    var latchesOn: Bool = true    <br>    ...</pre><p>Next, let’s call the <em>onDrag</em> when the knob has been dragged. Note that this will be called hundreds of times during the user’s dragging period, with a slightly different completion value each time. It must be passed a completion value (as discussed earlier) which can be calculated by <em>drag width / max. X offset</em>, and it has a maximum of 1. The following diagram visualizes this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8SPKDgO_gmLdJFhew0SJA.png" /></figure><p>Inside the drag gesture’s <em>onChanged</em> we should calculate the progress towards the end, and call <em>onDrag</em> with it:</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                ...<br><br>                // Call onDrag with the progress towards the end<br>                // - The actual offset / max offset<br>                let progress = min(value.translation.width / maxXOffset, 1)<br>                onDrag(progress)<br>            }<br>    }<br>}<br><br><br>#Preview {<br>    TutorialSliderButton(onDrag: { progress in<br>        print(&quot;Dragged \(((progress*100)).formatted())%&quot;)<br>    })<br>        .padding()<br>        .tint(.red)<br>}</pre><p>And when I drag, you see this in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*7wTlMpaJNrmcROv2cXaJdQ.gif" /><figcaption>As I drag, the progress towards the end increases</figcaption></figure><p>Now it is very easy to do the next stage, <strong>calling the <em>onComplete</em></strong> when the progress = 1 (knob dragged 100% toward the end):</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                ...<br><br>                // If the progress is 1 (complete)<br>                // - Call the onComplete function<br>                if progress &gt;= 1 {<br>                    onComplete()<br>                }<br>            }<br>    }<br>}</pre><p>In the console when dragging, I see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*s17-4RmYQNXbgkiYEZeMWA.gif" /></figure><p>You can see that the <em>onComplete</em> is only triggering when the progress is 100%, however it is being called multiple times. This is because after the user drags fully to the end, they keep their finger on the knob for a few seconds, then release it. In that time, they move the knob slightly which causes progress changes picked up by the <em>onChange</em> modifier. (Don’t worry as these have no effect on the knob’s offset as we limit the progress to a maximum of 1. If we didn’t use the <em>min(…, 1)</em> function you would see progress values &gt;1 being used.)</p><p>To solve this problem, let’s have a <strong>flag variable</strong> to keep track of whether the drag action was fully completed.</p><ul><li>Initially it will be false</li><li>When dragging it will also stay false</li><li>When the user drags 100% to the end, call the onComplete function <strong>then</strong> set it to true</li><li>Only call the <em>onComplete</em> if this flag variable is false</li><li>Reset it to false when the user releases their finger (in the drag gesture’s <em>onEnded</em>), so that the same logic can be used next time they drag.</li></ul><pre>struct TutorialSliderButton: View {<br>    ...<br>    @State private var didComplete = false<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                ...<br>                // ...<br>                if progress &gt;= 1 &amp;&amp; !didComplete {<br>                    onComplete()<br>                    didComplete = true<br>                }<br>            }<br>            .onEnded { value in<br>                didComplete = false<br>            }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*S6buj_KRJvJj_kmTcpLZdQ.gif" /></figure><p>Now, the <em>onComplete</em> is only called once, although there is another issue highlighted by the video clip — that is, after the interaction completed, the knob can still be dragged and cause the <em>onComplete</em> to be called a second time. To solve this issue there are 2 things we could do:</p><ul><li>in the drag gesture’s <strong><em>onChanged</em> </strong>add a guard statement at the top to <strong>ensure that <em>didComplete</em> is false</strong> — this stops the offset from being set by dragging and so the <em>onComplete</em> from happening again</li><li>in the <em>.gesture</em> modifier, <strong>pass in <em>isEnabled: !didComplete</em></strong> — when this is true, the gesture is recognized and SwiftUI calls the <em>onChanged</em> modifier when something happens. When false, SwiftUI <strong>ignores the gesture</strong> and so <em>onChanged</em> does not get called at all. This is a lot <strong>more efficient</strong>, so let’s write this line of code to fix the issue:</li></ul><pre>struct TutorialSliderButton: View {<br>    ...<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>                // KNOB<br>                Circle()<br>                    ...<br>                    .gesture(dragGesture(with: geom), isEnabled: !didComplete)<br>            ...<br>    }<br>    ...<br>}</pre><p>Now, after when user has completed the interaction they cannot complete further interactions of drag the knob at all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*OvDgnBnpZNnNGuoh8XAz1w.gif" /><figcaption>When dragging a second time, nothing happens</figcaption></figure><h3>Latching &amp; bouncing back</h3><h4>Bouncing back</h4><p>Next, we need to enable the knob to <strong>bounce back to its original position</strong> if it released before being dragged fully towards the end. I.e. if it is dragged 10, 40, or even 95% and released, its offset will be set to 0 again (with a nice animation).</p><p>For this, we will use the <em>onEnded</em> modifier for the drag gesture.</p><blockquote>Note: after investigation, I found this sequence:</blockquote><blockquote>• Knob dragged 100%</blockquote><blockquote>•<em> didComplete</em> set to true (in <em>onChanged</em>)</blockquote><blockquote>• the gesture is now <strong>disabled</strong>…</blockquote><blockquote>• …therefore the <strong><em>onEnded</em> does not get called</strong></blockquote><blockquote>This means that when dragging <strong>100%</strong>, <em>onEnded</em> will <strong>not</strong> be called, but it <strong>will</strong> be called if the interaction was not completed (where <em>didComplete = false</em> so the gesture is <strong>en</strong>abled).</blockquote><p>So to recap, <em>onEnded</em> will only be called when the drag gesture ends <strong>and the progress &lt; 100%</strong>.</p><p>This makes our goal easy: we can simply set the knob X offset to 0 in a <em>withAnimation</em> block — no need to re-calculate the progress and only reset the offset if progress &lt;100%:</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            .onChanged { value in<br>                ...<br>            }<br>            .onEnded { value in<br>                didComplete = false<br>                withAnimation(.spring(duration: 0.4, bounce: 0.2)) {<br>                    knobXOffset = 0<br>                }<br>            }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*KOVEqHfnC0vp6XHUtPZciw.gif" /></figure><h4>Disable latching</h4><p>So far we have made the button latch on for simplicity, but now we must do the following when latching is <strong>turned off</strong>:</p><ul><li><strong>keep the gesture enabled</strong> — we should <strong>not </strong>disable the gesture after sliding once. To do this we need to modify the boolean <em>isEnabled</em> input of <em>gesture</em> modifier.</li><li>when the gesture ends (in <em>onEnded</em>) <strong>set <em>didComplete</em> back to false</strong> again <strong>conditionally</strong>.</li></ul><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>                // KNOB<br>                Circle()<br>                    ...<br>                    .gesture(dragGesture(with: geom), isEnabled: !didComplete || !latchesOn)<br>            ...<br>    }<br>    <br>    <br>    private func dragGesture(with geomProxy: GeometryProxy) -&gt; some Gesture {<br>        DragGesture()<br>            ...<br>            .onEnded { value in<br>                // When it ends, firstly toggle the didComplete back to false, but ONLY if it should not latch on (in which case keeping didComplete to true would stop any more interaction)<br>                if !latchesOn &amp;&amp; didComplete {<br>                    didComplete = false<br>                }<br>                <br>                ...<br>            }<br>    }<br>}<br><br><br>#Preview {<br>    TutorialSliderButton(onComplete: {<br>        print(&quot;Slider-button onComplete triggered!&quot;)<br>    }, latchesOn: false)<br>        .padding()<br>        .tint(.red)<br>}</pre><p>In this code:</p><ul><li>I set the gesture’s <em>isEnabled</em> input to <em>!didComplete || !latchesOn</em>. This means, “<em>enable the gesture when the gesture is not completed or we are not latching on</em>”. I will also draw the truth table for this expression to make it a little clearer:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUOJjppEpD6qckxDvUuE9w.png" /><figcaption>Truth table for boolean equation shown</figcaption></figure><blockquote>Note: Another version of this expression would be <em>!(didComplete &amp;&amp; latchesOn)</em> — this is derived from <strong>De Morgan’s laws</strong> of:</blockquote><blockquote><strong><em>∙ !A &amp;&amp; !B = !(A||B)</em></strong></blockquote><blockquote><strong><em>∙ !A || !B = !(A&amp;&amp;B)</em></strong></blockquote><p>Now, as you can see from the screenshot, the toggle bounces back to the original position when latching is off:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*AfLm_KEHSNrNoomb2abudQ.gif" /><figcaption>Note: I set the <strong>latchesOn property to false</strong> in the #Preview, in the code sample above</figcaption></figure><h3>Adding the background &amp; foreground</h3><p>Another important aspect of the toggle slider is <strong>customizability</strong> — this includes being able to add views to the left &amp; right hand of the toggle that slide with it — these are the backgrounds &amp; foregrounds.</p><ul><li><strong>background</strong>: A view to display on the <strong>right-hand side</strong> of the knob, and slides right with the knob, as the <em>foregroundView</em> appears.<strong> Visible when not sliding.</strong></li><li><strong>foreground</strong>: A view to display on the <strong>left-hand-side</strong> of the knob, and is hidden to begin with when the knob is in its original position. As the user slides right and completion progress increases, the foreground view also is also slid right.</li></ul><p>Here is an example of the definitions of these terms, from the final product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*vj5vF24DDHmF85vU1QemCA.gif" /><figcaption>Background displays when not sliding. Foreground displays when sliding.</figcaption></figure><h4>Refactoring into a configuration</h4><p>Before we add these extra 2 views, let’s refactor our currnet code to be more customizable, allowing developers to change the track &amp; knob instead of the default monotone ones:</p><pre>public struct TutorialSliderButtonConfiguration {<br>    public let background: AnyView<br>    public let foreground: AnyView<br>    public let track: AnyView<br>    public let knob: AnyView<br>    <br>    public init&lt;Background: View, Foreground: View, Knob: View, Track: View&gt;(<br>        @ViewBuilder background: () -&gt; Background,<br>        @ViewBuilder foreground: () -&gt; Foreground,<br>        @ViewBuilder track: () -&gt; Track,<br>        @ViewBuilder knob: () -&gt; Knob<br>    ) {<br>        self.background = AnyView(background())<br>        self.foreground = AnyView(foreground())<br>        self.track = AnyView(track())<br>        self.knob = AnyView(knob())<br>    }<br>    <br>    public init(<br>        knobPadding: CGFloat = 8<br>    ) {<br>        self.background = AnyView(EmptyView())<br>        self.foreground = AnyView(EmptyView())<br>        self.track = AnyView(Capsule().fill(.tint.quaternary))<br>        self.knob = AnyView(Circle().fill(.tint).padding(knobPadding))<br>    }<br>       <br>    public init&lt;Background: View, Foreground: View&gt;(<br>        knobPadding: CGFloat = 8,<br>        @ViewBuilder background: () -&gt; Background,<br>        @ViewBuilder foreground: () -&gt; Foreground<br>    ) {<br>        self.background = AnyView(background())<br>        self.foreground = AnyView(foreground())<br>        self.track = AnyView(Capsule().fill(.tint.quaternary))<br>        self.knob = AnyView(Circle().fill(.tint).padding(knobPadding))<br>    }<br>}</pre><p>I created a configuration structure to hold all the nested views for the slider-button. I also added a number of initializers, so developers can choose wether to:</p><ul><li>pass in a customized background, foreground, knob and track, with views they provide</li><li>create the default (monotone) slider-button with a given knob padding.</li><li>create the default (monotone) slider-button with a given knob padding, and a foreground/background.</li></ul><p>Next, let’s make out button-slider accept this instead of a knob padding, and draw the knob / track from this struct instead of hardcoded defaults:</p><pre>struct TutorialSliderButton: View {<br>    var configuration: TutorialSliderButtonConfiguration = .init()<br>    var latchesOn: Bool = true // also reordered<br>    var onComplete: () -&gt; () = { }<br>    var onDrag: (Double) -&gt; () = { _ in }<br>    <br>    //MARK: - View properties<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK<br>                configuration.track<br>                // KNOB<br>                configuration.knob<br>                    ...<br>            }<br>        }<br>        ...<br>    }<br>    ...<br>}<br><br><br>#Preview {<br>    let config = TutorialSliderButtonConfiguration {<br>        // background<br>        EmptyView()<br>    } foreground: {<br>        EmptyView()<br>    } track: {<br>        Capsule()<br>            .fill(.gray.gradient)<br>            .frame(height: 10)<br>            .padding(8)<br>    } knob: {<br>        Image(systemName: &quot;heart.fill&quot;)<br>            .resizable()<br>            .aspectRatio(contentMode: .fit)<br>            .foregroundStyle(.pink.gradient)<br>            .padding(4)<br>    }<br><br>    TutorialSliderButton(configuration: config)<br>        .padding()<br>        .tint(.red) // has no effect<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*YaaPriFPM12p6vw7q2hhhQ.gif" /><figcaption>Here, <strong>latchesOn is true</strong></figcaption></figure><blockquote><strong>Important Note</strong>: I also <strong>changed the order of inputs</strong> — now <em>latchesOn</em> <strong>precedes</strong> the <em>onComplete</em> / <em>onDrag</em> closures.</blockquote><h4>Adding the background</h4><p>The background is simple — it should display <strong>over the top of the track</strong>, and slide right with the knob (although the track stays stationery), so we should offset it by the same amount as the knob:</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK + BACKGROUND<br>                ZStack {<br>                    // BACKGROUND<br>                    configuration.track<br>                    // BACKGROUND CONTENT<br>                    configuration.background<br>                        .offset(x: knobXOffset)<br>                }<br>                // KNOB<br>                ...<br>            }<br>        }<br>        ...<br>    }<br>    ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*v-p-wFbyLL51BL9Y-sHYUg.gif" /></figure><h4>Adding foreground</h4><p>This one is slightly trickier — the foreground should start off hidden (as it’s on the left of the knob) and appear as the user slides right. For this, we need to change the offset to take into account the foreground size. The diagram below illustrates this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUCS3AWz-Q3lL0xUwdxfFw.png" /></figure><p>In summary:</p><ul><li>the total foreground width = slider width - knob width</li><li>Foreground content offset = slider min. X - foreground width + knob X offset</li></ul><p>What we need to do is:</p><ul><li>put the foreground content somewhere in the ZStack — it doesn&#39;t really matter but we can put it under the knob for example</li><li>set the foreground’s max-width (as slider width - knob width)</li><li>access the foreground content’s actual width (with the .<em>onGeometryChange</em> modifier, just like the knob width).</li><li>offset the foreground as discussed</li></ul><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - View properties<br>    ...<br>    @State private var foregroundContentWidth: CGFloat = 0<br>    <br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK + BACKGROUND<br>                ...<br>                // FOREGROUND CONTENT<br>                // (starts off at the minX - width + knob width)<br>                // (width is the full slider width - knob width)<br>                configuration.foreground<br>                    .frame(maxWidth: geom.size.width - knobWidth)<br>                    .onGeometryChange(for: CGFloat.self, of: {<br>                        $0.size.width<br>                    }, action: {<br>                        self.foregroundContentWidth = $0<br>                    })<br>                    .offset(x: geom.frame(in: .local).minX - foregroundContentWidth + knobXOffset)<br><br>                // KNOB<br>                ...<br>            }<br>        }<br>        ...<br>    }<br>    ...<br>}<br><br>#Preview {<br>    let config = TutorialSliderButtonConfiguration {<br>        // background<br>        ...<br>    } foreground: {<br>        Image(systemName: &quot;checkmark.circle.fill&quot;)<br>            .resizable()<br>            .aspectRatio(contentMode: .fit)<br>            .frame(width: 40, height: 40)<br>            .foregroundStyle(.green.gradient)<br>            .background(.white, in: .circle)<br>    } track: {<br>        ...<br>    } knob: {<br>        ...<br>    }<br><br>    TutorialSliderButton(configuration: config)<br>        ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*VtVyi95j42HkwaaS8KicXQ.gif" /></figure><h4>Finishing touches!</h4><p>One of the 2 things I want to do is enable either the <strong>knob</strong> to be dragged, <strong>or the background</strong>. This is also very easy — we just need to apply the gesture to both elements, or even the whole <em>ZStack</em>:</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                // TRACK + BACKGROUND<br>                ...<br>                // FOREGROUND CONTENT<br>                ...<br><br>                // KNOB<br>                configuration.knob<br>                    ....<br>                    .offset(x: knobXOffset) // Set this BEFORE the gesture<br>            }<br>            .gesture(dragGesture(with: geom), isEnabled: !didComplete || !latchesOn)<br>        }<br>        ...<br>    }<br>    ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*5Sfvc2INzLFssGncazVqGA.gif" /></figure><p>The last thing to do is fix an <strong>issue with clipping &amp; transparency</strong>: if we go back to the <strong>default version</strong> (with the transparent track) the knob should be <strong>clipped inside the track</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*6MQRT5cdXvNcAanMXhQa2w.gif" /><figcaption>The <strong>desired</strong> effect</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*ZTdOVcnlWswz_xJIMDZg3w.gif" /><figcaption>The <strong>actual</strong> effect we have</figcaption></figure><p>However, this is <strong>not always not what we want</strong> — if the knob was clipped to the track in the heart example, we would get something like this, which is obviously unintended:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Vp8GFpHaUObnTJu63WgPgQ.png" /></figure><p>The best option is to use a <strong>boolean input property</strong> to control whether to clip the knob inside the track or not. This is our first step. The second step is of course clipping to the mask, with the <em>mask</em> modifier.</p><p>If you’re not familiar with masks, a simple description is “<em>a filter to display which parts of a view are visible and which are not. </em><strong><em>They control the opacity of layers masked by them.</em></strong>” Remember that last sentence! So, basically, <strong>wherever a mask is, contents can be seen</strong>.</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    var contentsClipped: Bool = false<br>    <br>    //MARK: - View properties<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        GeometryReader { geom in<br>            ZStack(alignment: .leading) {<br>                ...<br>            }<br>            .gesture(dragGesture(with: geom), isEnabled: !didComplete || !latchesOn)<br>            .mask {<br>                if contentsClipped {<br>                    // If we should clip the contents, mask it to the track<br>                    configuration.track<br>                }<br>                // If we should NOT clip to contents, clip to a filled rectangle instead<br>                else {<br>                    Rectangle()<br>                        .ignoresSafeArea()<br>                }<br>            }<br>        }<br>        ...<br>    }<br>    ...<br>}<br><br>#Preview(&quot;Basic--Clipped&quot;) {<br>    TutorialSliderButton(contentsClipped: true)<br>        .padding()<br>}</pre><p>Here:</p><ul><li>I firstly add the property (and set it to true in the preview)</li><li>I apply a mask to the <em>ZStack</em> containing all the elements</li><li>If the <em>ZStack</em> should be masked by the track (i.e. knob &amp; foreground/background <em>clipped</em> to it) then the mask is simply the track, so that the <strong><em>ZStack (including knob) </em>only appears inside the track</strong></li><li>If the <em>ZStack</em> should NOT be masked by the track (like in the heart example) then the mask should allow the whole knob/foreground/background to show. You could have found a way to conditionally add the mask modifier, but I found it easier to just clip them to a rectangle ignoring safe areas, so that they are essentially clipped to the whole screen.</li></ul><p>Here is the result of the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*GwaPpCEuOWyAaTHFWYoJwA.png" /></figure><p>It is somewhat unexpected because the opacity of the slider has been greatly reduced, now remember the sentence “<strong>Layer opacity = mask opacity</strong>”, so</p><ul><li>if the mask opacity is 1, the layer opacity if at least 1 (unless the layer reduces its opacity with its own modifier).</li><li>If mask opacity = 0.3, then they layer opacity also = 0.3.</li></ul><p>That is what is happening here — because the default track has a quaternary fill, its opacity is reduced by SwiftUI, so when masking to it, the knob and track have a reduced opacity.</p><p>To fix this, you can use a hack to make <strong>all visible parts of the track have an opacity of 1, just for the mask</strong>. For this you can use the <em>Canvas</em> API, and its alpha threshold filter. It takes in a threshold, and all pixels above this opacity (or alpha), have an opacity (alpha) of 1, and all pixels below have an alpha = 0.</p><pre>struct TutorialSliderButton: View {<br>    ...<br>    //MARK: - Body<br>    var body: some View {<br>        ...<br>            .mask {<br>                if contentsClipped {<br>                    // If we should clip the contents, mask it to that<br>                    trackOutline<br>                }<br>                ...<br>            }<br>        }<br>        ...<br>    }<br>    <br>    <br>    @ViewBuilder var trackOutline: some View {<br>        let id = UUID()<br>        <br>        Canvas { context, size in<br>            if let resolved = context.resolveSymbol(id: id) {<br>                context.addFilter(.alphaThreshold(min: 0.01))<br>                context.draw(resolved, at: CGPoint(x: resolved.size.width/2, y: resolved.size.height/2))<br>            } else {<br>                print(&quot;Cannot find the trackView when finding its outline&quot;)<br>            }<br>        } symbols: {<br>            configuration.track.tag(id)<br>        }<br>    }<br>    ...<br>}<br><br>#Preview(&quot;Basic--Clipped&quot;) {<br>    TutorialSliderButton(contentsClipped: true)<br>        .trackOutline<br>        .frame(height: 60)<br>        .padding()<br>}</pre><p>In this code:</p><ul><li>I create another property called <em>trackOutline</em> that is also a view</li><li>I use the <em>Canvas</em> view that takes in the <em>symbols</em> view-builder. The first closure is responsible for <strong>drawing something</strong> to a graphics context (<em>context</em>), and the <em>symbols</em> is responsible for <strong>providing views that can be drawn</strong>. Also, each view in the <em>symbols</em> needs a tag, so it can be retrieved in the first closure to be drawn.</li><li>In the first closure, I firstly access a view from the symbols closure with a given tag — in this case, the <em>configuration.track</em> view. This can be operated on including drawn to the drawing canvas. <em>context.resolveSymbol</em> returns nil if no symbols with the provided ID were found.</li><li>Secondly, I add the alpha threshold filter — <strong>remember</strong> that filters are applied before drawing content. It has a minimum threshold of 0.01 meaning pixels &gt;0.01 are rendered black (with full alpha), and below 0.01 have no alpha (i.e. opacity=0).</li><li>Thirdly, I <strong>calculate the position</strong> for the track to be drawn — <strong>remember</strong> that in the Canvas, point (0,0) is in the top-left corner of the context. However in views they draw, the center point is in the center. Therefore, if I set the position for the track to be <em>CGPoint.zero</em>, you would see only a quarter of it drawn in the top-left corner. Instead, the X position = half the track’s width and Y = half its height</li><li>Lastly, I draw it (with the filter applied) at the given point</li></ul><p>This code produces the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*0wshvSWWc6gB6YX-HnRv9w.png" /></figure><p>This will then be used as the <strong>mask</strong> to clip the content to.</p><p>With this preview, here is the <strong>output</strong>: (Note: I also made <em>trackOutline</em> private)</p><pre>#Preview(&quot;Basic--Clipped&quot;) {<br>    TutorialSliderButton(contentsClipped: true)<br>        .padding()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*OOm-paCWZg6ATIr51W-8HQ.gif" /></figure><h3>And we’re done!</h3><p>Thanks for reading this article — if you enjoyed, I would appreciate a round of applause 👏. I hope it all worked out for you!</p><h4>Slide to delete example (as shown in the cover image)</h4><pre>struct Person: Identifiable {<br>    let id = UUID()<br>    let string: String<br>    init(_ s: String) {<br>        self.string = s<br>    }<br>}<br><br>#Preview(&quot;Slide to delete example&quot;) {<br>    <br>    @Previewable @State var names = [&quot;John Doe&quot;, &quot;Jane Roe&quot;, &quot;Amy Johnson&quot;, &quot;Jacob Jones&quot;, &quot;Dexter Morgan&quot;].map { Person($0) }<br>    <br>    @Previewable @State var deletingPerson: Person?<br>        <br>    @Previewable @State var deletionSliderIcon = &quot;chevron.right&quot;<br>    <br>    @Previewable @State var colorMixAmount: CGFloat = 0.0<br>    <br>    <br>    let config = TutorialSliderButtonConfiguration {<br>        // background<br>        Text(&quot;Slide to delete&quot;)<br>            .foregroundStyle(.white.opacity(0.5))<br>    } foreground: {<br>        EmptyView()<br>    } track: {<br>        if #available(iOS 18.0, *) {<br>            RoundedRectangle(cornerRadius: 12)<br>                .fill(.red.mix(with: .yellow, by: colorMixAmount).gradient)<br>        } else {<br>            RoundedRectangle(cornerRadius: 12)<br>                .fill(.red.gradient)<br>        }<br>    } knob: {<br>        RoundedRectangle(cornerRadius: 8)<br>            .fill(.white.gradient)<br>            .padding(4)<br>            .aspectRatio(1, contentMode: .fit)<br>            .overlay {<br>                Image(systemName: deletionSliderIcon)<br>                    .foregroundStyle(.red.gradient)<br>                    .font(.headline)<br>                    .contentTransition(.symbolEffect)<br>            }<br>    }<br><br>    <br>    NavigationStack {<br>        ScrollView {<br>            LazyVGrid(columns: [GridItem(), GridItem()], spacing: 30) {<br>                ForEach(names) { person in<br>                    VStack {<br>                        Circle()<br>                            .fill(.gray.gradient)<br>                            .frame(maxWidth: 100, maxHeight: 100)<br>                        HStack {<br>                            Text(person.string)<br>                                .font(.headline)<br>                            <br>                            Button(&quot;Delete&quot;, systemImage: &quot;trash.fill&quot;) {<br>                                deletingPerson = person<br>                            }<br>                            .foregroundStyle(.red)<br>                            .labelStyle(.iconOnly)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>        .navigationTitle(&quot;People&quot;)<br>        .sheet(item: $deletingPerson) { person in<br>            NavigationStack {<br>                VStack {<br>                    Text(&quot;Are you sure you want to delete this person?&quot;)<br>                    <br>                    TutorialSliderButton(configuration: config) {<br>                        deletionSliderIcon = &quot;checkmark.circle.fill&quot;<br>                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>                            deletingPerson = nil<br>                        }<br>                        names.removeAll(where: { $0.id == person.id })<br>                    } onDrag: { completion in<br>                        colorMixAmount = completion / 4 // so that the maximum valiue if 0.25<br>                    }<br><br>                }<br>                <br>                .padding(.horizontal)<br>                .navigationTitle(person.string)<br>            }<br>            .presentationDetents([.fraction(0.4)])<br>            .onAppear {<br>                deletionSliderIcon = &quot;chevron.right&quot;<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*dk-Qw_RBxmeDeZ5LQxgkfw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c141624fb3c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a macOS Text-to-speech Converter]]></title>
            <link>https://medium.com/@danielcrompton5/create-a-macos-text-to-speech-converter-5d78274a0bff?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d78274a0bff</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[macos-development]]></category>
            <category><![CDATA[speech-synthesis]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 18:02:56 GMT</pubDate>
            <atom:updated>2025-02-16T18:02:56.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Js1r1IqkNhdpxKCw7HXRGA.gif" /><figcaption>The finished app</figcaption></figure><h3>Chapters:</h3><ol><li>Creating the basic UI</li><li>Text-to-speech</li><li>Changing the voice</li><li>Changing the speed</li><li>Pausing / Stopping</li></ol><h3>#1 — Creating the basic UI</h3><p>In a new macOS Xcode project, open <strong>ContentView.swift</strong> and add to a VStack:</p><ul><li>the app’s title — “Aloud”</li><li>a text editor</li><li>a play button</li></ul><p>Here is an <strong>example</strong>: (ContentView.swift)</p><pre>struct ContentView: View {<br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            <br>            Label(&quot;Aloud&quot;, systemImage: &quot;speaker.wave.2.bubble&quot;)<br>                .font(.largeTitle)<br>            <br>            TextEditor(text: .constant(&quot;Text&quot;))<br>            <br>            Button(&quot;Play&quot;, systemImage: &quot;play&quot;) { }<br>                .buttonStyle(.borderedProminent)<br>            <br>        }<br>        .padding()<br>        <br>    }<br>}</pre><p>Now, let’s <strong>make the window size</strong> in the entry point (AloudApp.swift):</p><pre>@main<br>struct AloudApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .frame(minWidth: 300, maxWidth: .infinity, minHeight: 350, maxHeight: .infinity)<br>        }<br>        .defaultSize(CGSize(width: 600, height: 400))<br>    }<br>}</pre><h4>In this code:</h4><ul><li>The <em>.frame(min/maxWidth, min/maxHeight)</em> sets the minimum size that the window can be scaled to by the cursor (when dragging in the corner). The maximum is infinity (the whole screen)</li><li>The <strong>.defaultSize</strong> sets the size when the window first appears.</li></ul><p>Here is the <strong>result</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_m8ld5ZIdzwb-IdePwiWVw.png" /><figcaption>The running app (600x400 size)</figcaption></figure><p>Let’s add some <strong>more styling</strong>:</p><p>(ContentView.swift)</p><pre><br>struct ContentView: View {<br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            <br>            Label(&quot;Aloud&quot;, systemImage: &quot;speaker.wave.2.bubble&quot;)<br>                .font(.system(size: 40, weight: .medium, design: .rounded))<br>                .foregroundStyle(.tint)<br>            <br>            TextEditor(text: .constant(&quot;Text&quot;))<br>                .textEditorStyle(.plain)<br>                .padding(12)<br>                .background {<br>                    RoundedRectangle(cornerRadius: 12)<br>                        .stroke(.gray)<br>                        .opacity(0.2)<br>                }<br>            <br>            Button {<br>            } label: {<br>                Label(&quot;Play&quot;, systemImage: &quot;play.fill&quot;)<br>                    .labelStyle(.iconOnly)<br>                    .font(.system(size: 40))<br>                    .padding()<br>                    .background(.tint, in: .circle)<br>            }<br>            .buttonStyle(.plain)<br>            <br>        }<br>        .font(.system(size: 16, weight: .light, design: .rounded))<br>        .padding()<br>        <br>    }<br>}</pre><p>(AloudApp.swift)</p><pre>@main<br>struct AloudApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .frame(minWidth: 300, maxWidth: .infinity, minHeight: 350, maxHeight: .infinity)<br>        }<br>        .defaultSize(CGSize(width: 600, height: 400))<br>        .windowStyle(.hiddenTitleBar)<br>        .windowBackgroundDragBehavior(.enabled)<br>    }<br>}</pre><p>Here is the <strong>result</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_22eTgAL8n75F6d2EMfmA.png" /><figcaption>With extra styling applied</figcaption></figure><h4>Adding a view model</h4><p>Now let’s add a view model to manage the text. Later on it will be used to keep track of the audio playing: (<strong>AloudViewModel.swift</strong>)</p><pre>@Observable<br>class AloudViewModel {<br>    var text = &quot;&quot;<br>}</pre><p>Now let’s <strong>replace the text editor’s constant binding</strong> with a binding to the text property in the view model: (ContentView.swift)</p><pre>struct ContentView: View {<br>    <br>    @State private var viewModel = AloudViewModel()<br>    var body: some View {<br>         ...<br>         TextEditor(text: $viewModel.text)<br>         ...<br>    }<br>}</pre><p>This is the basic app set up!</p><p>But I also want 2 buttons at the top right corner of the text field: one to <strong>paste</strong> the content of the clipboard and another to <strong>clear</strong> the text editor. Let’s do this:</p><pre><br>struct ContentView: View {<br>    ...<br>    var body: some View {<br>        <br>        ...<br>            <br>            TextEditor(text: $viewModel.text)<br>                .textEditorStyle(.plain)<br>            <br>                .overlay(alignment: .topTrailing) {<br>                    HStack(spacing: 0) {<br>                        Button(action: paste) {<br>                            Label(&quot;Paste&quot;, systemImage: &quot;clipboard&quot;)<br>                                .labelStyle(.iconOnly)<br>                                .padding(6)<br>                        }<br>                        <br>                        Button(action: clear) {<br>                            Label(&quot;Clear&quot;, systemImage: &quot;eraser&quot;)<br>                                .labelStyle(.iconOnly)<br>                                .padding(6)<br>                        }<br>                    }<br>                    .padding(.horizontal, 6)<br>                    .background(.thinMaterial, in: .capsule)<br>                    .buttonStyle(.plain)<br>                    .offset(x: -20) // so it doesn&#39;t cover the scroll indicator<br>                }<br>            <br>                ...<br>            <br>        }<br>        ...<br>        <br>    }<br>    <br>    <br>    private func paste() {<br>        if let string = NSPasteboard.general.string(forType: .string) {<br>            viewModel.text = string<br>        }<br>    }<br>    <br>    <br>    private func clear() {<br>        viewModel.text = &quot;&quot;<br>    }<br>}</pre><h4>In this code:</h4><p>Note that I am using the <em>NSPasteboard</em> API to get a string from the clipboard.</p><h3>#2 — Text to speech</h3><p>It is super easy to read aloud a string with Apple’s AI voices. You use the <strong>AVFoundation</strong> framework, and its <strong>AVSpeechUtterance</strong> and <strong>AVSpeechSynthesizer</strong> to do this:</p><pre>@Observable<br>class AloudViewModel {<br>    var text = &quot;&quot;<br>    private var speechSynthesizer: AVSpeechSynthesizer?<br>    <br>    func play() {<br>        let utterance = AVSpeechUtterance(string: text)<br>        speechSynthesizer = AVSpeechSynthesizer()<br>        speechSynthesizer?.speak(utterance)<br>    }<br>}</pre><h4>In this code:</h4><p>Note that I make the <em>speechSynthesizer</em> available to all of the aloud view model, because the <em>pause</em> and <em>stop</em> functions (which we will add later) will need to use it.</p><p>Now, we can call the <em>play</em> function with the play button in the view:</p><pre>struct ContentView: View {<br>    <br>    ...<br><br>    var body: some View {<br>            ...<br>            Button(action: viewModel.play) {<br>                Label(&quot;Play&quot;, systemImage: &quot;play.fill&quot;)<br>                    ...<br>            }<br>            .buttonStyle(.plain)<br>            ...<br>}</pre><p>That’s it! Give it a go, the play button works with either Xcode previews or running the app.</p><h3>#3 — Changing the voice</h3><p>We want to display a picker next to the play button to select a voice. We can list them with <strong><em>AVSpeechSynthesisVoice.speechVoices()</em></strong>. Try printing them off when content view appears. Here they are in a menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*7njhRpGDvhvcH2cjUV8bZA.png" /><figcaption>List of some of the AI voices</figcaption></figure><p>I will keep track of a selected voice in the view model, and <strong>assign it to the utterance</strong> so the utterance uses it to speak:</p><pre>@Observable<br>class AloudViewModel {<br>    var text = &quot;&quot;<br>    private var speechSynthesizer: AVSpeechSynthesizer?<br>    var voice: AVSpeechSynthesisVoice = AVSpeechSynthesisVoice(language: Locale.current.language.languageCode?.identifier ?? &quot;en&quot;) ?? AVSpeechSynthesisVoice(identifier: &quot;com.apple.voice.compact.en-GB.Daniel&quot;)!<br>    <br>    func play() {<br>        let utterance = AVSpeechUtterance(string: text)<br>        utterance.voice = voice<br>        <br>        speechSynthesizer = AVSpeechSynthesizer()<br>        speechSynthesizer?.speak(utterance)<br>    }<br>}</pre><h4>In this code:</h4><p>Note that I try to get the <strong>default voice for the current language</strong> (Locale.current), using <em>Daniel</em> as a fallback.</p><p>As you can see there are a lot of voices! So let’s split them up into <strong>sections, depending on their language</strong>. Firstly, I’ll add a static method to the AloudViewModel to group the voices by their language:</p><pre>@Observable<br>class AloudViewModel {<br>    ...<br>    <br>    func play() {<br>        ...<br>    }<br>    <br>    static func voices() -&gt; [String : [AVSpeechSynthesisVoice]] {<br>        let voices = AVSpeechSynthesisVoice.speechVoices()<br>        <br>        let grouped = Dictionary(grouping: voices) { voice in<br>            Locale.current.localizedString(forIdentifier: voice.language) ?? voice.language<br>        }<br>        <br>        return grouped<br>    }<br>}</pre><h4>In this code:</h4><p>I use a dictionary to group the array into different segments. Here is another example of how it is used <strong>from the </strong><a href="https://developer.apple.com/documentation/swift/dictionary/init(grouping:by:)"><strong>Apple docs</strong></a>:</p><pre>let students = [&quot;Kofi&quot;, &quot;Abena&quot;, &quot;Efua&quot;, &quot;Kweku&quot;, &quot;Akosua&quot;]<br>let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })<br>// [&quot;E&quot;: [&quot;Efua&quot;], &quot;K&quot;: [&quot;Kofi&quot;, &quot;Kweku&quot;], &quot;A&quot;: [&quot;Abena&quot;, &quot;Akosua&quot;]]</pre><p>Now, I can display a picker bound to the AloudViewModel’s voice:</p><pre>struct ContentView: View {<br>    <br>    @State private var viewModel = AloudViewModel()<br>    private static let groupedVoices = AloudViewModel.voices()<br>    <br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>                ...<br>            <br>            HStack(spacing: 20) {<br>                <br>                Picker(<br>                    &quot;Voice&quot;,<br>                    systemImage: &quot;person.wave.2.fill&quot;,<br>                    selection: $viewModel.voice<br>                ) {<br>                    <br>                    ForEach(Self.groupedVoices.keys.sorted(), id: \.self) { language in<br>                        <br><br>                        if let voices = Self.groupedVoices[language] {<br>                            Section {<br>                                ForEach(voices, id: \.identifier) { voice in<br>                                    Text(voice.name)<br>                                        .tag(voice)<br>                                }<br>                            } header: {<br>                                Text(language)<br>                            }<br>                        }<br>                        <br>                    }<br>                    <br>                    <br>                }<br>                <br>                ...<br>        <br>    }<br>    <br>    <br>    ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQSi9Ro7-lhxcE8M7H-6mg.png" /><figcaption>This is what the app looks like now!</figcaption></figure><h4>#4 — Changing the Speed</h4><p>Let’s do something similar with speed: we can use a <em>rate</em> property of the AVSpeechUtterance and set it to a Float.</p><p>I firstly define some constants in the view model:</p><pre>@Observable<br>class AloudViewModel {<br>...<br>    var speed: Float = 0.1<br>    <br>    func play() {<br>        ...<br>        utterance.rate = speed<br>        ...<br>    }<br>    <br>    static let slowSpeed: Float = 0.07<br>    static let mediumSpeed: Float = 0.1<br>    static let fastSpeed: Float = 0.13<br>}</pre><p>Now let’s display a picker in the view:</p><pre>Picker(&quot;Speed&quot;,<br>       systemImage: &quot;gauge.with.dots.needle.33percent&quot;,<br>       selection: $viewModel.speed) {<br>    <br>    Group {<br>        Label(&quot;Slow&quot;, systemImage: &quot;tortoise&quot;)<br>            .tag(AloudViewModel.slowSpeed)<br>        Label(&quot;Medium&quot;, systemImage: &quot;hare&quot;)<br>            .tag(AloudViewModel.mediumSpeed)<br>        Label(&quot;Fast&quot;, systemImage: &quot;bolt&quot;)<br>            .tag(AloudViewModel.fastSpeed)<br>    }<br>    .labelStyle(.iconOnly)<br>}<br>.pickerStyle(.segmented)</pre><p>I would also like to <strong>split up the view </strong>into subviews to make it more manageable:</p><pre><br>struct ContentView: View {<br>    ...<br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            <br>            ...<br>            <br>            HStack(alignment: .bottom, spacing: 10) {<br>                <br>                voicePicker()<br>                                               <br>                controlButton(icon: &quot;play.fill&quot;, title: &quot;Play&quot;, size: 40, action: viewModel.play)<br>                               <br>                speedPicker()<br>                <br>            }<br>            <br>        }<br>        ...<br>        <br>    }<br>    <br>    <br>    ...<br>    <br>    <br>    @ViewBuilder private func voicePicker() -&gt; some View {<br>        Picker(<br>            &quot;Voice&quot;,<br>            systemImage: &quot;person.wave.2&quot;,<br>            selection: $viewModel.voice<br>        ) {<br>            <br>            ForEach(Self.groupedVoices.keys.sorted(), id: \.self) { language in<br>            <br>                <br>                if let voices = Self.groupedVoices[language] {<br>                    Section {<br>                        ForEach(voices, id: \.identifier) { voice in<br>                            Text(voice.name)<br>                                .tag(voice)<br>                        }<br>                    } header: {<br>                        Text(language)<br>                    }<br>                }<br>                <br>            }<br>            <br>            <br>        }<br>    }<br>    <br>    <br>    @ViewBuilder private func speedPicker() -&gt; some View {<br>        Picker(&quot;Speed&quot;,<br>               systemImage: &quot;gauge.with.dots.needle.33percent&quot;,<br>               selection: $viewModel.speed) {<br>            <br>            Group {<br>                Label(&quot;Slow&quot;, systemImage: &quot;tortoise&quot;)<br>                    .tag(AloudViewModel.slowSpeed)<br>                Label(&quot;Medium&quot;, systemImage: &quot;hare&quot;)<br>                    .tag(AloudViewModel.mediumSpeed)<br>                Label(&quot;Fast&quot;, systemImage: &quot;bolt&quot;)<br>                    .tag(AloudViewModel.fastSpeed)<br>            }<br>            .labelStyle(.iconOnly)<br>        }<br>        .pickerStyle(.segmented)<br>    }<br>    <br>    <br>    @ViewBuilder private func controlButton(icon: String, title: String, size: CGFloat, action: @escaping () -&gt; ()) -&gt; some View {<br>        <br>        Button(action: action) {<br>            Label(title, systemImage: icon)<br>                .labelStyle(.iconOnly)<br>                .font(.system(size: size))<br>                .foregroundStyle(.white)<br>                .padding()<br>                .background(.tint, in: .circle)<br>        }<br>        .buttonStyle(.plain)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yna_2ieMPh6R7ydS70kH_w.png" /><figcaption>This is the view now. It also works in light mode!</figcaption></figure><h4>#5 — Pause &amp; Stop</h4><p>Firstly, I’ll add a <strong>pause &amp; stop button</strong> next to the play button:</p><pre><br>struct ContentView: View {<br>    ...<br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            <br>            ...<br>            <br>            HStack(alignment: .bottom, spacing: 20) {<br>                <br>                voicePicker()<br>                     <br>                HStack(alignment: .bottom, spacing: 10) {<br>                    controlButton(icon: &quot;stop.fill&quot;, title: &quot;Stop&quot;, size: 20, action: viewModel.stop)<br>                    <br>                    controlButton(icon: &quot;play.fill&quot;, title: &quot;Play&quot;, size: 40, action: viewModel.play)<br>                    <br>                    controlButton(icon: &quot;pause.fill&quot;, title: &quot;Pause&quot;, size: 20, action: viewModel.pause)<br>                }<br>                <br>                speedPicker()<br>                <br>            }<br>        ...<br>    }<br>}</pre><p>Now, in the view model, we need to <strong>keep track of state</strong>:</p><pre>@Observable<br>class AloudViewModel {<br>    <br>    enum State {<br>        case none, playing, paused<br>    }<br>    <br>    var state = State.none<br>...<br>}</pre><p>It’s also important that we <strong>disable certain controls</strong> (namely text editor, voice and rate picker) while speaking — we can use the state for this:</p><pre> <br>struct ContentView: View {<br>    <br>    ...<br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            <br>            ...<br>            <br>            TextEditor(text: $viewModel.text)<br>                .disabled(viewModel.state != .none) // playing or paused<br>                .overlay(alignment: .topTrailing) {<br>                    if viewModel.state == .none {<br>                        HStack(spacing: 0) {<br>                            ...<br>                        }<br>                        ...<br>                        .animation(.easeOut, value: viewModel.state)<br>                        .transition(.scale)<br>                    }<br>                }<br>            <br>            HStack(alignment: .bottom, spacing: 20) {<br>                <br>                voicePicker()<br>                    .disabled(viewModel.state != .none) // playing or paused<br>                     <br>                ...<br>                <br>                speedPicker()<br>                    .disabled(viewModel.state != .none) // playing or paused<br>                <br>            }<br>         ...<br>    }<br>    ...<br>}</pre><p>We now need to make sure the state is in sync with the speech synthesizer — we can make the view model the synthesizer’s <strong>delegate</strong> for this, and respond to it playing, and pausing, and even stopping. At this stage I will also <strong>write code to stop, and pause the speech</strong>:</p><pre><br>@Observable<br>class AloudViewModel: NSObject { // INHERIT FROM NSOBJECT<br>    ...<br>    func play() {<br>        ...<br>        speechSynthesizer.delegate = self<br>        ...<br>    }<br>    <br>    func pause() {<br>        speechSynthesizer?.pauseSpeaking(at: .word)<br>    }<br>    <br>    func stop() {<br>        speechSynthesizer?.stopSpeaking(at: .immediate)<br>    }<br>    <br>    ...<br>}<br><br><br>extension AloudViewModel: AVSpeechSynthesizerDelegate {<br>    <br>    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {<br>        print(&quot;didStart&quot;)<br>        state = .playing<br>    }<br>    <br>    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {<br>        print(&quot;didPause&quot;)<br>        state = .paused<br>    }<br>    <br>    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {<br>        print(&quot;didFinish&quot;)<br>        state = .none<br>    }<br>}</pre><h4>In this code:</h4><ul><li>Note that when pausing and stopping, we can pick a <strong>boundary</strong> — either instantly or after the current word finishes.</li><li>I also need to remember to set the delegate for the speech synthesizer to <em>self</em></li></ul><p>Now, let’s show or <strong>hide the play/pause buttons depending on the state</strong> — with some fancy <strong>animations</strong>:</p><pre><br>struct ContentView: View {<br>    <br>    @State private var viewModel = AloudViewModel()<br>    <br>    private static let groupedVoices = AloudViewModel.voices()<br>    <br>    var body: some View {<br>        <br>        VStack(spacing: 20) {<br>            ...     <br>                HStack(alignment: .bottom, spacing: 10) {<br>                    <br>                    if viewModel.state != .none {<br>                        controlButton(icon: &quot;stop.fill&quot;, title: &quot;Stop&quot;, size: 20, action: viewModel.stop)<br>                            .transition(.blurReplace)<br>                    }<br>                    <br>                    if viewModel.state == .playing {<br>                        controlButton(icon: &quot;pause.fill&quot;, title: &quot;Pause&quot;, size: 40, action: viewModel.pause)<br>                            .disabled(viewModel.text.isEmpty)<br>                            .transition(.blurReplace)<br>                    } else {<br>                        controlButton(icon: &quot;play.fill&quot;, title: &quot;Play&quot;, size: 40, action: viewModel.play)<br>                            .transition(.blurReplace)<br>                    }<br>                }<br>                .animation(.easeOut, value: viewModel.state)<br>                ...<br>    }<br>    ...<br>}</pre><h4>In this code: (&amp; How animations work)</h4><p>I apply an ease out animation (which controls the <em>animation curve</em>), then a transition to the buttons — blur replace (which looks very nice) that controls <em>how</em> the buttons will animate in/out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VTX_LW_639GZbilj.gif" /><figcaption><a href="https://help.figma.com/hc/en-us/articles/360051748654-Prototype-easing-and-spring-animations">Curtousy of Figma</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Js1r1IqkNhdpxKCw7HXRGA.gif" /></figure><p>I hope you enjoyed building this with me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d78274a0bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to draw a circle section in SwiftUI Shape]]></title>
            <link>https://medium.com/@danielcrompton5/how-to-draw-a-circle-section-in-swiftui-shape-ed7bdb260b8e?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed7bdb260b8e</guid>
            <category><![CDATA[circle]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[shapes]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[section]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 12:31:36 GMT</pubDate>
            <atom:updated>2024-12-08T12:31:36.191Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article I will provide the code for the circle’s section you see below, and an understanding of how it works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAQeGKvh5tZ0Jx2oh1jEwQ.png" /><figcaption>The circle section you’ll learn how to build</figcaption></figure><p>The code to produce this circle section is:</p><pre>struct CircleSegment: Shape {<br>    let completion: CGFloat<br>    var isClockwise = true<br>    <br>    nonisolated func path(in rect: CGRect) -&gt; Path {<br>        <br>        // If the completion is 1, draw a circle<br>        if completion == 1 {<br>            return Circle().path(in: rect)<br>        }<br>        <br>        // If the completion is 0, return an empty path<br>        if completion == 0 {<br>            return Path()<br>        }<br>        <br>        <br>        return Path { path in<br>            <br>            // Now draw an arc with a given radius<br>            let center = CGPoint(x: rect.midX, y: rect.midY)<br>            <br>            path.addArc(<br>                center: center, // Compass needle is at the center of the rectangle (page)<br>                radius: min(rect.width / 2, rect.height / 2), // Keeping the aspect ratio of 1, the smaller of the 2 sides halved<br>                startAngle: .degrees(-90), // In SwiftUI, angles start at 90 degrees<br>                endAngle: .degrees(completion * 360 - 90.0), // Subtract 90 to offset the angle starting at -90 degrees<br>                clockwise: !isClockwise // SwiftUI clockwise works opposite<br>            )<br>            <br>            // Now draw a line to the middle<br>            path.addLine(to: center)<br>            <br>            // Now close it off<br>            path.closeSubpath()<br>            <br>        }<br>    }<br>}<br></pre><p>If you’d like to preview the shape:</p><pre>#Preview(&quot;Circle segment&quot;) {<br>    CircleSegment(completion: 0.3)<br>//        .fill(.tint)<br>        .stroke(Color.red, lineWidth: 5)<br>}</pre><h3>In this code</h3><p>To begin with, I create a structure called <em>CircleSegment</em> that conforms to the <em>Shape</em> protocol (the same protocol SwiftUI’s default shapes like <em>Rectangle</em>, <em>Capsule</em>, <em>Circle</em> etc. conform to). This forces us to implement the <em>path(in:)</em> method.</p><p>The structure takes as a parameter wether to draw the segment clockwise or not, and the completion (which is a normalized <em>CGFloat</em> in the range 0 to 1 and represents the radius).</p><h4>Inside the <em>path(in:)</em> method:</h4><p>We start by doing some simple input validation which could potentially make our code a little more efficient.</p><ul><li>Firstly, if the completion is 0, then no path needs to be drawn so an empty one is returned</li><li>Secondly, if the completion is 1, then a whole circle can be returned. I use SwiftUI’s default <em>Circle</em> for this, and call its <em>path(in:)</em> to return the path for a complete circle.</li></ul><p>Therefore, if the completion was between 0 and 1, then we know we need to draw our very own path:</p><ul><li>Before drawing, we find the center of the drawing rectangle. <br><strong>You can imagine the <em>rect</em> input to <em>path(in:)</em> as a piece of paper. </strong>This piece of paper has a width, height, X position in space, and Y position. It also has a midX and midY which are the middle values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySwd9zB4Yw8CXtnvN4fM6g.png" /><figcaption>Analogy of <em>rect</em> as a piece of paper</figcaption></figure><ul><li>We draw an arc (part of a circle) with:<br>- the <strong>center</strong> as the center of the page, <br>- the <strong>radius</strong> as the shorter side of the page’s width / height (halved, to maintain a 1:1 aspect ratio)<br>- the <strong>start angle</strong> as -90˚ (to account for SwiftUI’s drawing mechanism starting at what we consider 90˚)<br>- the <strong>end angle</strong> as <em>completion</em> ✖️ 360, with 90˚ subtracted to account for the -90˚ start angle<br>- the <strong>clockwise</strong> as the opposite of the clockwise input; SwiftUI’s draws clockwise arcs anti-clockwise</li></ul><p>Imaging the <em>addArc</em> method controlling a compass; the needle in the center of the page (rect) and the pencil starting at the start angle and finishing at the end angle.</p><p>The last thing we need to do is close the path (which automatically moves back to the start point on a straight line).</p><p>Now, we are done! Feel free to fill or stroke the circle section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed7bdb260b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Share content to an Instagram story from an iOS app]]></title>
            <link>https://medium.com/@danielcrompton5/share-content-to-an-instagram-story-from-an-ios-app-d55b1e10e68a?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55b1e10e68a</guid>
            <category><![CDATA[share]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[instagram-stories]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 22:15:44 GMT</pubDate>
            <atom:updated>2024-12-03T10:18:59.255Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article you’ll learn how to share content from a SwiftUI or UIKit iOS app to your Instagram story without using a ShareSheet — you’ll go straight from your app to Instagram!</h4><h3>Step 1: Create a Meta Developer account</h3><ul><li>Go to <a href="https://developers.facebook.com/">Facebook Developer</a> and from the top right corner, <strong>create a new Facebook developer account</strong> if you haven’t already &amp; complete all the authentication steps.</li><li>You may be prompted to <strong>create a new “application”</strong>. Press OK to create an application and procees with its steps. Or, if you aren’t prompted go to the <a href="https://developers.facebook.com/apps/">Facebook Developer Apps page</a> where you can create a new app:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEuG2_Do48xPT_d-xZn2SQ.png" /><figcaption>Press the green “Create App” button to create an app.</figcaption></figure><ul><li>When you have an app created, go to it and then using the sidebar, navigate to <strong>Settings &gt; Basic</strong>. At the bottom of the page, press a small grey button <strong>“Add platform”</strong>, which brings up a popup from which you can<strong> select “iOS”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3oi3tDO2XI6KvZw9T9D0mg.png" /><figcaption>In the Settings &gt; Basic (sidebar) I scrolled down to see the “+ Add platform” button, which I pressed to make the iOS box appear in settings. From here, I pasted my bundle ID into the field and left the others blank.</figcaption></figure><ul><li>An iOS box will have been added to the app’s settings and you can <strong>paste the bundle ID into the relevant field</strong>, leaving the <em>iPad</em>/<em>iPhone Store ID</em> blank for now. <br><strong>When the app is ready to be put into Live mode, add the App Store ID into this field.</strong></li><li>Press “Save changes” at the bottom</li></ul><h3>Step 2: Setting up your app</h3><ul><li>In the app settings in your app’s dashboard in Meta developer page, <strong>copy the app ID and paste it in Xcode</strong> as a global constant.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzRDiURq0M_poMMeHrpKfQ.png" /><figcaption>Copy the “App ID” field to Swift</figcaption></figure><pre>// important to send to instagram<br>let kInstagramAppId = &quot;1245017093459344&quot;</pre><ul><li>Go to the app’s <strong>Info.plist</strong> file (or project settings &gt; Into on newer Xcode versions) and <strong>add the key Queried URL Schemes </strong>and the value “<strong>instagram-stories</strong>”.<br><a href="https://developers.facebook.com/docs/instagram-platform/sharing-to-stories">This is documented here.</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e8oNRoTSznoC2N-bQH0Dg.png" /><figcaption>Notice the “<strong>Queried URL Schemes</strong>” key with a value as “<strong>instagram-stories</strong>”</figcaption></figure><h3>Step 3: Code to open image in Instagram</h3><p>Now in a SwiftUI view, (or UIKit storyboard) you can <strong>add a button</strong> to open an image in Instagram, for example:</p><pre>import SwiftUI<br><br>// important to send to instagram<br>fileprivate let kInstagramAppId = &quot;1245017093459344&quot;<br><br><br>struct InstaView: View {<br>    <br>    // Store image URL<br>    private let imageURL = URL(string: &quot;https://softauthor.com/wp-content/uploads/2021/08/CSS-Background-Image-Full-Screent-With-background-Image-1536x1355.png&quot;)!<br>    <br>    // Store image data<br>    @State private var imageData: Data?<br><br>    // Instagram URL<br>    let instagramURL = URL(string: &quot;instagram-stories://share?source_application=\(kInstagramAppId)&quot;)!<br>    <br>    var body: some View {<br>        <br>        VStack {<br>            if let imageData,<br>               let uiImage = UIImage(data: imageData) {<br>                <br>                // Display the image when it has been retrieved<br>                Image(uiImage: uiImage)<br>                    .resizable()<br>                    .scaledToFit()<br>                <br>            }<br>            <br>            Button(&quot;Open in instagram&quot;, action: openInInstagram)<br>                .disabled(imageData == nil)<br>            <br>        }<br>        .task {<br>            do {<br>                let (data, _) = try await URLSession.shared.data(from: imageURL)<br>                self.imageData = data<br>            } catch {<br>                print(&quot;Cannot get image: \(error)&quot;)<br>            }<br>                    <br>        }<br>        <br>    }<br>    <br>    <br>    private func openInInstagram() {<br>        <br>    }<br>}<br><br>#Preview {<br>    InstaView()<br>}</pre><h4>What this code does:</h4><ul><li>Store the Meta app ID associated with the current app</li><li>Store the Instagram URL (used later) which can be used in deep linking for our app to open Instagram. <br><strong>Note you MUST provide an app ID into this URL, otherwise Instagram will not open the content you provide.<br></strong><a href="https://developers.facebook.com/docs/instagram-platform/sharing-to-stories#:~:text=Beginning%20in%20January%202023,their%20content%20to%20Instagram,-.%20%20To">This is said clearly in the documentation.</a></li><li>Store an image URL and image data (<strong>only for testing purposes</strong>); <em>in a real app, you would most likely fetch an image from the internet and keep a reference to its data</em>.</li><li>When the view appears, load the image using URLSession (<strong>only for tests</strong>)</li><li>Display the image retrieved if it exists</li><li>Display a button which will call a method <em>openInInstagram</em> (currently empty). It is disabled if the content has not yet been fetched.</li></ul><h4>Opening Instagram:</h4><pre>private func openInInstagram() {<br>    guard let imageData else { return }<br>    <br>    let pasteboardItems = [<br>        &quot;com.instagram.sharedSticker.backgroundImage&quot;: imageData<br>    ]<br>    // copy to clipboard<br>    UIPasteboard.general.setItems([pasteboardItems])<br>    <br>    if UIApplication.shared.canOpenURL(instagramURL) {<br>        UIApplication.shared.open(instagramURL)<br>    }<br>}</pre><ul><li>Firstly, we unwrap the <em>imageData</em> variable</li><li>We create a dictionary containing the image’s data and <strong>copy it to the clipboard</strong> (pasteboard). Instagram will then read the data from it.</li><li>Then we make sure we can open the Instagram URL (standard pattern in opening URLs)</li><li>If we <em>can</em> open Instagram, we <em>do</em>, and Instagram will pre-populate the story with the background image you set!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Rm_mKdGOvC6jFzHq5P69iA.gif" /><figcaption>Pressing the “Instagram” button opens the image in Instagram for you to edit &amp; post!</figcaption></figure><h4>Bonus: Adding stickers</h4><p>Adding a sticker is as simple as adding the key “<strong>com.instagram.sharedSticker.stickerImage</strong>” to the <strong>pasteboardItems</strong> dictionary (defined in the above code snippet)!</p><p>Thanks for reading, Daniel!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55b1e10e68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the mean average of an array in Swift]]></title>
            <link>https://medium.com/@danielcrompton5/find-the-mean-average-of-an-array-in-swift-2d631ad4ed13?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d631ad4ed13</guid>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[average]]></category>
            <category><![CDATA[mean]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 19:02:56 GMT</pubDate>
            <atom:updated>2024-11-21T19:03:32.361Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to find the mean of a Swift array with reusable code that applies to any floating point type</h4><pre>import Foundation<br><br><br>extension Array where Element: FloatingPoint {<br>    <br>    func mean() -&gt; Element {<br>        reduce(0, +) / Element(count)<br>    }    <br>}</pre><h4>Logic to find the mean:</h4><ul><li>Mean = Sum of elements in array ➗ Number of elements summed</li><li>Firstly, <em>reduce(0, +)</em> finds the sum of elements</li><li>Then the sum is divided by the count (which is number of elements in the array)</li></ul><h4>Hard: “extension where” syntax:</h4><p>We extend Array only <em>where</em> the <em>Element</em> conforms to <em>FloatingPoint</em>. Note <em>Element</em> is the type of element stored in the array (e.g. in<em> [Int]</em>, the <em>Element</em> is <em>Int</em>, and in <em>[CGFloat]</em> the <em>Element</em> is <em>CGFloat</em>).</p><p>This means the extension methods/computed properties (i.e. <em>mean()</em>) will only be available when the <em>where</em> condition is true.</p><p><strong>Conformance to FloatingPoint means that the reduce method can be called, and the type can be initialized.</strong></p><p>This allows those methods to be called as we know that elements of the array will include them.</p><p>The <em>Element(count)</em> converts the count (<em>Int</em>) to the same type as the element (For example, in <em>[Double]</em> types, this is just like calling <em>Double(count)</em>). It is essential for both sides of the <em>/</em> operator to be the same type, so we need to convert the Int to the Element’s type.</p><h4>If you’re confused?</h4><p>If you want to read more about the “extension where” syntax, <a href="https://www.swiftbysundell.com/articles/specialized-extensions-using-generic-type-constraints/"><strong>John Sundell</strong> wrote an article</a> all about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d631ad4ed13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a drawing app with PencilKit & more!]]></title>
            <link>https://medium.com/@danielcrompton5/create-a-drawing-app-with-pencilkit-more-5c5a2a8a4738?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c5a2a8a4738</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[pencilkit]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 21:36:44 GMT</pubDate>
            <atom:updated>2025-01-16T11:47:07.276Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to create a basic drawing UI that can be implemented as a part of any other app, for iOS &amp; iPadOS.</h4><h4>Hi all. In this article you will learn:</h4><ul><li>How to use <strong>PencilKit</strong> with SwiftUI to create a simple drawing UI</li><li>How to present the <strong>PKToolPicker</strong></li><li>How to save drawings to the <strong>photo library</strong></li><li>How to persist the drawings in <strong>SwiftData</strong></li><li>How to bring up a <strong>share sheet</strong> with your drawing</li></ul><p>I’m so excited to tell you about this!</p><h3>Chapter 1: Use PencilKit with SwiftUI</h3><h4>What is PencilKit?</h4><p>PencilKit is Apple’s framework that allows a user to draw with their finger or an Apple Pencil. <strong>Summarizing the </strong><a href="https://developer.apple.com/documentation/pencilkit"><strong>documentation</strong></a> (which I’d still recommend reading):</p><ul><li>A <strong>PKCanvasView</strong> is a UIView that you can draw on. Set the <em>drawingPolicy</em> to <em>anyInput</em> to allow finger drawing</li><li>A PKCanvasView holds a drawing which is a <strong>PKDrawing</strong>. This (although very self-explanatory) represents the user’s drawing</li><li>PKDrawing holds a list of <strong>PKStrokes</strong> which have <strong>PKStrokePaths</strong></li><li>PKDrawing is <strong>Codable</strong> so can be saved to CoreData or SwiftData</li><li><strong>PKToolPicker</strong> is the tool picker palette that can be used to change the tool (like a brush), the width, color etc. This can be created and associated with the canvas view</li></ul><h4>Creating a UIViewRepresentable:</h4><pre>import SwiftUI<br>import PencilKit<br><br>struct CanvasView: UIViewRepresentable {<br>        <br>    func makeUIView(context: Context) -&gt; PKCanvasView {<br>        let canvasView = PKCanvasView()<br>        // Allow finger drawing<br>        canvasView.drawingPolicy = .anyInput<br>        <br>        return canvasView<br>    }<br>    <br>    func updateUIView(_ canvasView: PKCanvasView, context: Context) {<br>    }<br>       <br>}</pre><blockquote><strong>CanvasView.swift</strong></blockquote><h4>In this code:</h4><ul><li>A UIViewRepresentable is used to place a UIKit view (in this case PKCanvasView) in a SwiftUI context</li><li>In the <em>makeUIView</em> (which is called when creating the view) we create &amp; return a PKCanvasView object</li><li>We set the <strong>drawingPolicy</strong> of the canvas to anyInput to allow finger drawing</li></ul><h4>Code in action</h4><p>Let’s <strong>create a ContentView which will use the CanvasView</strong>, then create a ContentView in the app entry.</p><pre>//MARK: - Canvas usage<br><br>struct ContentView: View {<br>    var body: some View {<br>        CanvasView()<br>    }<br>}</pre><blockquote><strong>Appending to CanvasView.swift</strong></blockquote><pre>import SwiftUI<br><br>@main<br>struct iOS_AppApp: App {<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>    <br>}</pre><blockquote><strong>iOS_AppApp.swift</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaceVDHqw7i8pJ9AKdcnmQ.gif" /><figcaption><strong>Running the app</strong>, we see a blank view in a navigation stack where the user can draw with their finger, using the default black stroke.</figcaption></figure><h3>Chapter 2: Presenting the PKToolPicker</h3><p>This is <strong>trickier than it sounds</strong> and it took me a while to figure out how to make it work. Even now I’m not sure why the solution works.</p><h4>The bug</h4><p>In this code, the tool picker <strong>will not appear</strong>, as many people on Reddit/StackOverflow/Apple forums are saying:</p><pre>func makeUIView(context: Context) -&gt; PKCanvasView {<br>    // Create canvas<br>    let canvasView = PKCanvasView()<br>    // Allow finger drawing<br>    canvasView.drawingPolicy = .anyInput<br>    <br>    // Create a tool picker<br>    let toolPicker = PKToolPicker()<br>    // Make the tool picker visible<br>    toolPicker.setVisible(true, forFirstResponder: canvasView)<br>    // Make the canvas respond to tool changes<br>    toolPicker.addObserver(canvasView)<br>    // Make the canvas active -- first responder<br>    canvasView.becomeFirstResponder()<br>    <br>    return canvasView<br>}</pre><p><em>The output is the same as in the screen recording above.</em></p><p><em>Note: code explanations later.</em></p><h4>The fix</h4><p>The fix is simple:<strong> Move the declaration for toolPicker to outside the makeUIView method</strong>.</p><p><em>I don’t know exactly what the problem is but my guess is that the </em><strong><em>canvas keeps a weak reference to the tool picker</em></strong><em> and so when the picker is defined in makeUIView, when that scope ends, it is deallocated. I doubt this because it is not documented about a weak property of PKCanvasView to a tool picker. However the documentation does not include private properties and it may be a private declaration.</em></p><p>Now the code should be <em>(note I also moved the canvasView declaration outside too as we’ll need it in updateUIView later)</em>:</p><pre>struct CanvasView: UIViewRepresentable {<br>    private let canvasView = PKCanvasView()<br>    private let toolPicker = PKToolPicker()<br>    <br>    func makeUIView(context: Context) -&gt; PKCanvasView {<br>        // Allow finger drawing<br>        canvasView.drawingPolicy = .anyInput<br>        <br>        // Make the tool picker visible<br>        toolPicker.setVisible(true, forFirstResponder: canvasView)<br>        // Make the canvas respond to tool changes<br>        toolPicker.addObserver(canvasView)<br>        // Make the canvas active -- first responder<br>        canvasView.becomeFirstResponder()<br>        <br>        return canvasView<br>    }<br>    <br>    func updateUIView(_ canvasView: PKCanvasView, context: Context) {<br>    }<br>       <br>}</pre><h4>In this code:</h4><ul><li>In the default initializer for the struct, the canvas and tool picker are created</li><li>in <em>makeUIView</em>, the canvas is configured to allow finger drawing</li><li>The tool picker is also configured: firstly, set to appear, and then adds the canvas as an observer to notifications it publishes (mainly tool changes)</li><li>The canvas becomes first responder to send touch inputs to it.</li></ul><p>Note also that when using the CanvasView (<em>i.e. in ContentView</em>) <strong>styling it (for example, setting the frame or giving it a stroke) applies to the canvas but not the tool picker</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJk5ELuocnAFtg7umPJrow.gif" /><figcaption>Running the code, we see a bottom toolbar. <strong>on iPad, it appears as a floating palette which can be dragged &amp; relocated</strong>.</figcaption></figure><h4>Showing/hiding the tool picker</h4><p>It is a good idea to provide a way to hide or show the tool picker in usages of CanvasView; we should be able to provide a <strong>binding</strong> to a boolean property that, when changed, shows or hides the tool picker.</p><pre>struct CanvasView: UIViewRepresentable {<br>    @Binding var toolPickerShows: Bool<br>    <br>    private let canvasView = PKCanvasView()<br>    private let toolPicker = PKToolPicker()<br>    <br>    func makeUIView(context: Context) -&gt; PKCanvasView {<br>        // Allow finger drawing<br>        canvasView.drawingPolicy = .anyInput<br>        <br>        // Make the tool picker visible or invisible depending on toolPickerShows<br>        toolPicker.setVisible(toolPickerShows, forFirstResponder: canvasView)<br>        // Make the canvas respond to tool changes<br>        toolPicker.addObserver(canvasView)<br>        <br>        // Make the canvas active -- first responder<br>        if toolPickerShows {<br>            canvasView.becomeFirstResponder()<br>        }<br>        <br>        return canvasView<br>    }<br>    <br>    func updateUIView(_ canvasView: PKCanvasView, context: Context) {<br>        // Called when SwiftUI updates the view, (makeUIView(context:) called when creating the view.)<br>        // For example, called when toolPickerShows is toggled:<br>        // so hide or show tool picker<br>        <br>        toolPicker.setVisible(toolPickerShows, forFirstResponder: canvasView)<br>        toolPicker.addObserver(canvasView)<br>        if toolPickerShows {<br>            canvasView.becomeFirstResponder()<br>        } else {<br>            canvasView.resignFirstResponder()<br>        }<br>    }<br>       <br>}<br><br>//MARK: - Canvas usage<br><br>struct ContentView: View {<br>    @State private var toolPickerShows = true<br>    <br>    var body: some View {<br>        NavigationStack {<br>            CanvasView(toolPickerShows: $toolPickerShows)<br>                .navigationTitle(&quot;Drawing&quot;)<br>                .toolbar {<br>                    ToolbarItem(placement: .topBarTrailing) {<br>                        Button(&quot;\(toolPickerShows ? &quot;Hide&quot; : &quot;Show&quot;) tool picker&quot;, systemImage: &quot;wrench.adjustable&quot;) {<br>                            toolPickerShows.toggle()<br>                        }<br>                    }<br>                }<br>        }<br>    }<br>}</pre><h4>In this code:</h4><ul><li>The CanvasView has a binding to a boolean value — <em>toolPickerShows</em></li><li>The <em>updateUIView</em> method uses the <em>toolPickerShows</em> property to hide or show the tool picker.<br>Don’t forget: <strong>The <em>updateUIView</em> method is called when SwiftUI refreshes the view due to a change in state</strong>, for example, toggling <em>toolPickerShows</em>.<strong> </strong>However, <em>makeUIView </em>is called when creating the view in the first place (normally only once).</li><li>When updating the view, the tool picker is shown or hidden, depending on the new value of toolPickerShows.</li><li>In ContentView, a button is placed in the toolbar to show or hide the tool picker</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62Z1ej0vF4Vz2XoZ7ad8Vg.gif" /><figcaption>Running the code, you will see that when the toolbar button is pressed, the tool picker hides or shows</figcaption></figure><h4>Reading/writing to the drawing in usages of CanvasView</h4><p>It is <strong>important that SwiftUI can read the drawing from the PKCanvasView</strong> <strong>and write to it too</strong>. The canvasView in CanvasView stores a <em>drawing</em> property that is a PKDrawing.</p><p>Let’s add a binding to this drawing in CanvasView:</p><pre>struct CanvasView: UIViewRepresentable {<br>    @Binding var drawing: PKDrawing<br>    @Binding var toolPickerShows: Bool<br>    // ...<br>}</pre><pre>struct ContentView: View {<br>    //...<br>    @State private var drawing = PKDrawing()<br>    <br>    // ...<br>    CanvasView(drawing: $drawing, toolPickerShows: $toolPickerShows)<br>    // ...<br>}</pre><p>Now, in usages of CanvasView we are able to provide a drawing to the canvas initially, however, when the <em>canvasView.drawing</em> changes (when drawing), <strong>the drawing binding property is not updated</strong>, meaning they will be out of sync.</p><p>To fix this, we can update the drawing binding property whenever the canvasView drawing changes. Let’s <strong>make a coordinator</strong> that conforms to <em>PKCanvasViewDelegate</em> and implements the <em>canvasViewDrawingDidChange</em> method, which is <strong>called whenever the canvas’s drawing is edited</strong>. We simply want to <strong>update the drawing property:</strong></p><pre>struct CanvasView: UIViewRepresentable {<br>    // ...<br>    <br>    func makeUIView(context: Context) -&gt; PKCanvasView {<br>        // ...<br>        <br>        // Set the coordinator as the canvas&#39;s delegate<br>        canvasView.delegate = context.coordinator<br>        <br>        // ...<br>    }<br>    <br>    func updateUIView(_ canvasView: PKCanvasView, context: Context) {<br>        // ...<br>    }<br>    <br>    <br>    //MARK: - Coordinator<br>    <br>    class Coordinator: NSObject, PKCanvasViewDelegate {<br>        var drawing: Binding&lt;PKDrawing&gt;<br>        <br>        init(drawing: Binding&lt;PKDrawing&gt;) {<br>            self.drawing = drawing<br>        }<br>        <br>        func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {<br>            drawing.wrappedValue = canvasView.drawing<br>        }<br>    }<br>    <br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(drawing: $drawing)<br>    }<br>       <br>}</pre><h4>In this code:</h4><ul><li>A <em>Coordinator</em> class is embedded in the CanvasView, and keeps a binding to a PKDrawing. Now we need to pass the drawing from CanvasView to the coordinator delegate.<br>Reminder: <strong>Coordinators are often used when the UIView inside the UIViewRepresentable needs a delegate</strong>.</li><li>The Coordinator conforms to <em>PKCanvasViewDelegate</em> and implements <em>canvasViewDrawingDidChange</em>, which sets the coordinator’s (and canvas’s) <em>drawing</em> property to the canvas view’s new drawing.</li><li>In my code the makeCoordinator instantiates Coordinator passing in a binding to the canvas’s drawing.<br>When any UIViewRepresentable contains a <em>Coordinator</em> class, <strong>you must implement the <em>makeCoordinator</em> function</strong> to create one.</li><li>In CanvasView makeUIView, the canvasView’s delegate is set to the coordinator in the context.</li></ul><p>Now, the drawing binding property is being updated by the canvas view’s delegate (the coordinator), and we now need to <strong>handle cases when SwiftUI updates the drawing</strong>. Remember, when SwiftUI changes state (i.e. changes its drawing property) the <em>updateUIView</em> is triggered. There, let’s update the canvas view’s drawing</p><pre>struct CanvasView: UIViewRepresentable {<br>    @Binding var drawing: PKDrawing<br>    @Binding var toolPickerShows: Bool<br>    <br>    // ...<br>    <br>    func makeUIView(context: Context) -&gt; PKCanvasView {<br>        // ...<br>    }<br>    <br>    func updateUIView(_ canvasView: PKCanvasView, context: Context) {<br>        // ...<br>        <br>        // Also called when users of CanvasView change the drawing propety<br>        // so update the canvas view&#39;s drawing if necessary<br>        if drawing != canvasView.drawing {<br>            canvasView.drawing = drawing<br>        }<br>    }<br>    <br>    <br>    // ...<br>       <br>}</pre><h4>In this code:</h4><ul><li>When updating the view, firstly check if the drawing has been set by SwiftUI (it has been if the drawing property differs from the canvas view’s drawing).</li><li>Now update the canvas view’s drawing to the new drawing that SwiftUI set.</li></ul><h4>Clearing the drawing</h4><p>We made this super easy by making sure that when we update the drawing from CanvasView usages, the changes are reflected in the CanvasView.</p><p>To update the drawing, we can simply create a <strong>new blank PKDrawing</strong>:</p><pre>struct ContentView: View {<br>    // ...<br>    CanvasView(drawing: $drawing, toolPickerShows: $toolPickerShows)<br>        // ...<br>        .toolbar {<br>            // ...<br>            <br>            ToolbarItem(placement: .topBarTrailing) {<br>                Button(&quot;Erase all&quot;, systemImage: &quot;trash&quot;) {<br>                    drawing = PKDrawing()<br>                }<br>            }<br>        }<br>    // ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YHAHWUSvWkxLVyswtudEw.gif" /><figcaption>Running the app we see the toolbar button and when pressed, clears the drawing erasing everything</figcaption></figure><h3>Chapter 3: Saving drawings</h3><p>This is very simple and easy to do and involves 2 main stages:</p><h4>1. Access photo library:</h4><p>Firstly, your app needs permission to add photos to the photo library.</p><p>Go to the <strong>Info.plist</strong> and add the key “<strong>Privacy — Photo Library Additions Usage Description</strong>”. Set the value to the message that appears in the alert that asks a user for permission to save photos to their photo library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyQkgbGvF25hkCApRYnWkg.gif" /><figcaption>Setting a value for “Privacy — Photo Library Additions Usage Description<strong>”</strong></figcaption></figure><h4>2. Call method to save photo</h4><p>Since saving a drawing is an action related to a PKDrawing, I will extend PKDrawing with a method to save it.</p><pre>import PencilKit<br>import UIKit<br><br>extension PKDrawing {<br>    <br>    func saveToPhotoLibrary() {<br>        // Generate a UIImage from the drawing (since only UIImages can be saved to photo library):<br>        let uiImage = self.image(from: self.bounds, scale: 1)<br>        <br>        // Call a UIKit method to save an image<br>        UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)<br>    }<br>    <br>}</pre><blockquote><strong>PKDrawing+saveToPhotoLibrary.swift</strong></blockquote><h4>In this code:</h4><ul><li>A method called <em>saveToPhotoLibrary</em> is added to PKDrawing.</li><li>It firstly converts the drawing to a UIImage</li><li>Then, it calls <em>UIImageWriteToSavedPhotosAlbum</em> with the UIImage to save it to photos<br><em>Note: </em><a href="https://www.youtube.com/watch?app=desktop&amp;v=q-eQWNsutjY"><em>Paul Hudson explains the UIWriteToSavedPhotosAlbum method in a YouTube video</em></a><em>.</em></li></ul><h4>Code in action:</h4><p>I will add a save button to the toolbar to save it to photos:</p><pre>struct ContentView: View {<br>    // ...<br><br>    CanvasView(drawing: $drawing, toolPickerShows: $toolPickerShows)<br>        // ...<br>        .toolbar {<br>            // ...<br>            <br>            ToolbarItem(placement: .topBarLeading) {<br>                Button(&quot;Save drawing&quot;, systemImage: &quot;arrow.down.doc&quot;) {<br>                    drawing.saveToPhotoLibrary()<br>                }<br>            }<br>        }<br><br>    // ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUiRH9TlfXa5X5MtoqptCQ.gif" /><figcaption>Running the code, when pressing the save photo button, firstly an alert asks the user for photo library permissions, then if they allow, the image is saved to Photos</figcaption></figure><h3>Chapter 4: Persisting drawings in SwiftData</h3><p>Although <em>PKDrawing</em> is <em>Codable</em>, SwiftData <em>should be able to </em>save the <em>PKDrawing</em>s in a <em>Model</em> with ease, however as with many of Apple’s types, SwiftData is unable to save them in a model.</p><p>Therefore inside an @Model class it is important to save the data representation instead of the actual PKDrawing:</p><pre>import Foundation<br>import SwiftData<br>import PencilKit<br><br><br>@Model<br>class DesignModel {<br>    private var drawingData: Data<br>    var drawing: PKDrawing {<br>        get {<br>            (try? PKDrawing(data: drawingData)) ?? PKDrawing()<br>        }<br>        <br>        set {<br>            drawingData = newValue.dataRepresentation()<br>        }<br>    }<br>    <br>    init(drawingData: Data) {<br>        self.drawingData = drawingData<br>        <br>    }<br>    <br>    init(drawing: PKDrawing) {<br>        self.drawingData = drawing.dataRepresentation()<br>    }<br>    <br>    init() {<br>        drawingData = Data()<br>    }<br>}</pre><h3>Chapter 5: Share drawings with a share sheet</h3><p><a href="https://codewithchris.com/swiftui-sharelink/">Joash at CodeWithChris</a> describes how to create share sheet with ShareLink in SwiftUI very well and I’d highly recommend reading his article, since I will not explain how it works, but just implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHjDZg_XPhrv8iaRypGQMw.png" /><figcaption>CWC ShareLink article</figcaption></figure><p>The ShareLink requires items to be <a href="https://developer.apple.com/documentation/coretransferable/transferable">Transferable</a>, which is a protocol from IOS 16+ that describes how a type can be transferred via share links, paste buttons, drag/drop etc. <strong>PKDrawing is not Transferable but</strong> <em>(SwiftUI)</em><strong><em> </em>Image is.</strong></p><p>Let’s add an extension to PKDrawing to include a method called <em>image</em> that returns a SwiftUI image that can be shared.</p><pre>// ...<br>import SwiftUI<br><br>extension PKDrawing {<br>    <br>    func saveToPhotoLibrary() {<br>        // ...<br>    }<br>    <br>    func image() -&gt; Image {<br>        let uiImage = self.image(from: self.bounds, scale: 1)<br>        return Image(uiImage: uiImage)<br>    }<br>    <br>}</pre><blockquote><strong>PKDrawing+saveToPhotoLibrary.swift </strong>renamed to<strong> PKDrawing+extensions.swift</strong></blockquote><p>Now we can add a share link to the toolbar in ContentView (Note that since the <strong>share sheet includes an option to save the image</strong>, I have removed the toolbar button to do so):</p><pre>struct ContentView: View {<br>    // ...<br><br>    CanvasView(drawing: $drawing, toolPickerShows: $toolPickerShows)<br>        // ...<br>        .toolbar {<br>            // ...<br>            <br>            ToolbarItem(placement: .topBarLeading) {<br>                let image = drawing.image()<br>                ShareLink(item: image,<br>                          subject: Text(&quot;Drawing&quot;),<br>                          message: Text(&quot;Drawn with MyApp!&quot;),<br>                          preview: SharePreview(&quot;Drawing&quot;, image: image)) {<br>                    Label(&quot;Share&quot;, systemImage: &quot;square.and.arrow.up&quot;)<br>                }<br>            }<br>            <br>//            ToolbarItem(placement: .topBarLeading) {<br>//                Button(&quot;Save drawing&quot;, systemImage: &quot;arrow.down.doc&quot;) {<br>//                    drawing.saveToPhotoLibrary()<br>//               }<br>//            }<br>        }<br>    // ...<br>}</pre><h4>In this code:</h4><ul><li>Another <em>ToolbarItem</em> is added to the toolbar, this time containing a <em>ShareLink</em> instead of button</li><li>The share link’s <strong>label </strong>is what appears on the UI<strong> </strong>and is in the trailing closure</li><li>The share link’s <strong>item </strong>is what to be shared — in this case, the image</li><li>The <strong>subject</strong> is used when sharing the item via email — it is the subject field for an email</li><li>The <strong>message </strong>is the body for the email or text message</li><li>The <strong>preview </strong>represents the top part for the share sheet, with the drawing’s image for the icon &amp; some text as the label first argument.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*lTdX1kP3pqM3nLmUvwkQ_Q.png" /><figcaption>This is what the <strong>SharePreview</strong> represents</figcaption></figure><p>Thanks for reading this article, I hope it was helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c5a2a8a4738" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make font bold in ioOS 15]]></title>
            <link>https://medium.com/@danielcrompton5/how-to-make-font-bold-in-ioos-15-e5b24f933049?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5b24f933049</guid>
            <category><![CDATA[ios15]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[boldfont]]></category>
            <category><![CDATA[italic-font]]></category>
            <category><![CDATA[fonts]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 16:04:06 GMT</pubDate>
            <atom:updated>2024-07-25T16:04:18.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to make font bold in iOS 15</h3><p>I was recently working on a project that needed to support iOS 15, and had been using the .bold() &amp; .fontWeight(_:) modifiers all over my project but then realised… Oh… .bold() &amp; .fontWeight(_:) were introduced for iOS 16. So what to do instead?</p><h4>Solution:</h4><p>Instead of using .bold() modifier, use the <strong>Font.weight(.bold)</strong>, e.g.</p><pre>Text(&quot;Fly Swatting\nKeyboard Game&quot;)<br>    .multilineTextAlignment(.center)<br>    .font(.fLogo.weight(.bold))<br>    .foregroundStyle(.grayForeground)</pre><p>Similarly, you can access <strong>italic versions like this too</strong>, i.e.:</p><pre>.font(.fLogo.weight(.bold).italic())</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5b24f933049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add custom fonts to a SwiftUI project for iOS & macOS]]></title>
            <link>https://medium.com/@danielcrompton5/how-to-add-custom-fonts-to-a-swiftui-project-for-ios-macos-258eecd39f0d?source=rss-c26e14afc8c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/258eecd39f0d</guid>
            <category><![CDATA[fonts]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Danielcrompton]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 21:54:50 GMT</pubDate>
            <atom:updated>2024-07-19T21:54:50.591Z</atom:updated>
            <content:encoded><![CDATA[<p>I have seen many articles on this topic but I have not yet seen one that explains all 3 stages properly, <strong>and</strong> how to do it on macOS too…</p><h3>Watch the video here</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fph8lGiRtTFQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dph8lGiRtTFQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fph8lGiRtTFQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/988bbd07d15b16ab84eefcffc8319876/href">https://medium.com/media/988bbd07d15b16ab84eefcffc8319876/href</a></iframe><h3>Stage 1 — Find a font &amp; add it to Xcode</h3><h4>Finding a font</h4><p>There are a lot of places to get fonts from online, some paid and some free, some good quality, andsome less so. <strong>Google fonts</strong> is a safe place to find 100% free fonts for use in apps, and you don’t need to register to download them. Furthermore, <strong>Figma, most people’s favourite design program, uses fonts from Google fonts</strong>, therefore your designs can become reality!</p><p>Firstly, go to <a href="https://fonts.google.com/">Google fonts</a> and use the filters to find a font. If you know the name of a font, e.g. from a Figma design, you can search for it. Add fonts to the basket and then download all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xfz1vUrBhjm2FqegYbSag.gif" /><figcaption>Finding and downloading 2 fonts from Google fonts</figcaption></figure><h4>Font file formats</h4><p>Any font file you have can be used; t<strong>hese are .ttf or .otf files</strong>. If you encounter a .woff or .woff2 file (which are web open fonts and are highly compressed) you will need to use an online conversion tool to convert them to a .ttf or .otf, both formats work with <strong>no difference between them in how they are handled</strong>.</p><h4>Adding fonts to Xcode</h4><p>This stage is easy: all you need to do is unzip the folder downloaded from Google fonts (or any other site) and then find the font files.</p><p>Drag them into a fonts folder in an Xcode SwiftUI project (for any OS) and make sure they are <strong>added to the main target and copied if needed</strong>.</p><p>You can add them to a folder if you’d like, this does not matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wV-0uI9RaGHQPJA1FuXR5Q.gif" /><figcaption>Adding font files to Xcode</figcaption></figure><h4>Which fonts?</h4><p>I always recommend adding the:</p><ul><li>Regular</li><li><em>Italic</em></li><li><strong>Bold</strong></li><li><strong><em>Bold Italic</em></strong></li></ul><p>weights (variants — or thicknesses of a font) to <strong>make use of the <em>.bold()</em> &amp; <em>.italic()</em> modifiers</strong>.</p><p>If you want to make use of all the weights, e.g. using the <em>.fontWeight()</em> modifier, you can add more, but I still recommend including an italic version.</p><h3>Stage 2 — Update Info.plist</h3><p>This varies depending on if you’re designing for iOS or macOS, but either way, <strong>open the main target settings, then the <em>Info</em> tab</strong> and:</p><h4>For iOS</h4><p>Add they key <strong>“Fonts provided by application”</strong> and copy the file names (including extension) of all the font files for the values.</p><blockquote>Note that to add a key, you can hover over any of the default keys and press the small + button.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_3RxZO-JNIvb3QHfD7Y0w.gif" /><figcaption>Adding the “Fonts provided by application” key to an iOS target</figcaption></figure><h4>For macOS</h4><p>Add the key “Application fonts resource path” and set it to the <strong>path relative to the bundle’s Resources directory, where the fonts can be located</strong>. For example, if the fonts are directly located in the resources folder (in the case of the GIF below) the path of the fonts is . (dot). If the fonts were copied to a <em>Fonts</em> directory in the resources directory (via a copy files build phase), the value would be <em>Fonts/</em>.</p><p>In this GIF, the fonts are directly located in Resources (even though they’re inside a Fonts folder in the Xcode project — no, the Xcode project does not represent the bundle structure).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6Vjp-O6fooHDlfa1n-LCQ.gif" /><figcaption>Adding the “Application fonts resource path”, where the fonts are directly located in Resources</figcaption></figure><p>In this video, I ensure the fonts are not copied to the Resources folder of the app bundle, but a Resources/Fonts/ folder. Therefore the value of the “Application fonts resource path” key is “Fonts/”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rOBOaiu5Cp4RHcIGhfs7Q.gif" /><figcaption>Copying the fonts to Resources/Fonts/</figcaption></figure><h3>Stage 3 — Use custom fonts</h3><h4>Extending SwiftUI Font</h4><p>Make an extension of SwiftUI Font, and add some static constants to reference the added fonts. This is done via <em>Font.custom</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnnvtM7uy7eFtBwtiWqLzA.gif" /><figcaption>Creating a Font extension &amp; accessing custom fonts</figcaption></figure><blockquote><em>Note: </em><strong><em>You do not need to add static constants for all your font weights</em></strong><em> — e.g. adding myFont1Regular, myFont1Italic, myFont1Bold, myFont1BoldItalic is not necessary: you only need the regular version. Using the .bold() / .italic() / .fontWeight() is still possible as SwiftUI find the other weights in your bundle.</em></blockquote><h4>Font naming</h4><p>When naming your font extensions, I like to append a letter to the start to signify the project I am in — this makes sure that you are not extending Font with names that already exist, e.g. <em>largeTitle</em> would become <em>qLargeTitle</em> if in a quiz game.</p><p><strong>I found this issue with SwiftUI previews — if I named a Font extension with a name that already exists, like <em>largeTitle</em>, the previews would crash (despite there being not errors in the code and the simulator working).</strong></p><h4>Finding your post-script name</h4><p>The <em>name</em> parameter for <em>Font.custom</em> refers to the <strong>Post-Script name</strong> of the font, <strong>NOT</strong> the file name. This is a unique identifier for fonts, however Google fonts always names font files with the post script names, therefore if you are using Google fonts, you can easily copy the file name (without extension) for the <em>name</em> parameter.</p><p>If you are downloading fonts from elsewhere, you changed the file name accidentally, or the <em>name</em> you tried does not properly access the font (<strong>you will see the default system font instead</strong>) you should ensure you have the correct name:</p><ol><li>Open the font file with Font Book (this is the default)</li><li>Install the font and find it listed (in the <em>My Fonts</em> section in the sidebar — use the search tool to help)</li><li>Open the inspector and drop down the <em>Identifiers</em> section, and copy the post-script name; use this as the <em>name</em> parameter for <em>Font.custom</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8B3cUtPnB-L9Wc_bStmJw.gif" /><figcaption>Finding the font post-script name</figcaption></figure><h3>You’re done!</h3><p>Congrats on following these stages, <strong>please leave a comment if this worked, or if it did not</strong>. Now all that’s left is to <strong>use the custom fonts</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuVETlU5hx6TY6buAGhbzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf90hGfqRFPTMTmDcSoD8A.gif" /><figcaption>Using custom fonts</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=258eecd39f0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>