<?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 Nunzio Ricci on Medium]]></title>
        <description><![CDATA[Stories by Nunzio Ricci on Medium]]></description>
        <link>https://medium.com/@nunzio.ricci.2000?source=rss-eaadbb01d7ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*igd3picqKJsmoqEO9OMsLg.png</url>
            <title>Stories by Nunzio Ricci on Medium</title>
            <link>https://medium.com/@nunzio.ricci.2000?source=rss-eaadbb01d7ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:06:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nunzio.ricci.2000/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[Swift Property Wrappers]]></title>
            <link>https://medium.com/@nunzio.ricci.2000/swift-property-wrappers-46997d54f5ec?source=rss-eaadbb01d7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/46997d54f5ec</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[wrapper]]></category>
            <category><![CDATA[property]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Nunzio Ricci]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 18:27:14 GMT</pubDate>
            <atom:updated>2023-07-20T22:04:25.881Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are just starting to write your apps in SwiftUI you may be wondering what @State, @StateObject, @AppStorage are. In this article I will try to explain in a simple way what property wrappers are, what problem they solve, and how to create your own.</p><h3>What wrappers do</h3><p>Let’s say that we have a wrapper called <em>@Wrapper</em> what happens when you wrap a variable with it?</p><pre>@Wrapper var variable: Int</pre><pre>var _variable = Wrapper()<br>var variable: Int {<br>    get {<br>        _variable.wrappedValue<br>    }<br>    set {<br>        _variable.wrappedValue = newValue<br>    }<br>}</pre><p>Two blocks above have pretty the same behavior. When we wrap a variable we are declaring that the var we are wrapping is a computed property that simply access to the <em>wrappedValue</em> property of a <em>Wrapper</em> instance. <em>_variable</em> is an effective variable that you can indeed use in the code (you can try with @<em>State</em> variables in SwiftUI).</p><h3>Why we need them?</h3><p>Sometimes we need to customize access to a variable. For example, we may need to perform checks on the input data when we write it, we may need to refresh the value each time we read it, and so on. In these cases as we have seen there are alternatives: we can use computed properties, didSet, willSet, etc. Wrappers are just a way to take this behavior that we can define as we prefer and reuse it whenever we need it.</p><h3>But how can we create it?</h3><p>Creating it is pretty simple you have to create an object:</p><pre>@propertyWrapper<br>struct Wrapper {<br>    var wrappedValue: Int = 0<br>}</pre><p>As you can see is only a struct wrapped with @<em>propertyWrapper</em> and with a property called <em>wrappedValue</em>. Obviously this is the variable we spoke about in the previous chapter, the one that you access by calling the wrapped variable.</p><p>But written like this isn’t really useful, right? So lets se a real use case:</p><pre>@propertyWrapper<br>struct Wrapper {<br>    var value: Int = 0<br>    <br>    var wrappedValue: Int {<br>        get { value }<br>        set { value = min(value, 100) }<br>    }<br>}</pre><p>Now we declared a new property called <em>value</em> and the <em>wrappedValue</em> is a computed property that set value with 100 as max possible value.</p><p>Come on, now do a couple of tests and come back here as soon as you encounter any problems.</p><h3>Set initial value</h3><p>If you tried something like this:</p><pre>@Wrapper var variable = 0</pre><p>You probably noticed that Xcode gives you this error: Extra argument ‘wrappedValue’ in call. If you remember in What wrappers do, when we wrap a variable we create an instance of the wrapper in the variable _variable. In this case when we give an initial value to the property this value is passed to the initializer of Wrapper in that way:</p><pre>var _variabe = Wrapper(wrappedValue: 0)<br>var variable: Int {<br>    get {<br>        _variable.wrappedValue<br>    }<br>    set {<br>        _variable.wrappedValue = newValue<br>    }<br>}</pre><p>So we can update the wrapper in the previous chapter with our new knowledge:</p><pre>@propertyWrapper<br>struct HighScore {<br>    var value: Int<br>    <br>    var wrappedValue: Int {<br>        get { value }<br>        set { value = min(value, 100) }<br>    }<br>    <br>    init() {<br>        self.value = 0<br>    }<br>    <br>    init(wrappedValue: Int) {<br>        self.value = wrappedValue<br>    }<br>}</pre><p>So now we created two new initializers:</p><ul><li>The first one is the initializer that is called when you don’t get an initial value;</li><li>The second one is the initializer that take the initial value and save it in the value.</li></ul><h3>Custom initializer</h3><p>What if we want to pass custom values to our wrapper? If you already seen a wrapper like <em>@AppStorage</em> you might have noticed that it accepts an attribute, es.:</p><pre>@AppStorage(&quot;highScore&quot;) var highScore: Int = 0</pre><p>As you can see in the brackets we have a string that is passed to <em>AppStorage</em> initializer. How it works? If you are on Xcode you can do <strong>option+click</strong> on <em>@AppStorage</em> to see the definition and we can find this code:</p><pre>public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) where Value == Int</pre><p>From this you will have understood the mechanism: When you passing an argument to the wrapper is the same thing as passing to initializer.</p><p>To be clear, back to our example, let’s say we want to add a way to set a custom maximum value:</p><pre>@propertyWrapper<br>struct HighScore {<br>    var value: Int<br>    var maxValue: Int<br><br>    var wrappedValue: Int {<br>        get { value }<br>        set { value = min(value, maxValue) }<br>    }<br>    <br>    init(wrappedValue: Int = 0, max maxValue: Int = 100) {<br>        self.value = wrappedValue<br>        self.maxValue = maxValue<br>    }<br>}</pre><p>We are going to use it in this way:</p><pre>@Wrapper(max: 100) var highScore = 0</pre><p>In conclusion, I hope this article has clarified for you the basics of property wrappers in Swift. If you are interested in learning more specifically about SwiftUI wrappers, I have written an article that you can find <a href="https://medium.com/@nunzio.ricci.2000/understanding-swiftui-persistency-wrappers-through-their-procedural-alternative-b94c80434dd7">here</a>. Goodbye and may the forced optional unwrapping be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46997d54f5ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I turned a meme into a SwiftUI component]]></title>
            <link>https://medium.com/@nunzio.ricci.2000/how-i-turned-a-meme-into-a-swiftui-component-2aaded7ea06c?source=rss-eaadbb01d7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aaded7ea06c</guid>
            <category><![CDATA[swiftui-animation]]></category>
            <category><![CDATA[memes]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Nunzio Ricci]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 10:30:32 GMT</pubDate>
            <atom:updated>2023-07-05T00:37:11.442Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you know those nights when you scrolled through social media until 3 a.m.? A few days ago I had the misfortune of seeing the wrong meme at 2:59 a.m. and facing an unexpected challenge for the next 2 hours and 15 minutes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOT9nW1r6CWY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOT9nW1r6CWY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOT9nW1r6CWY%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/03ccb99a9ba4b1b73156c11fd44c9b8f/href">https://medium.com/media/03ccb99a9ba4b1b73156c11fd44c9b8f/href</a></iframe><p>Why? Maybe because it’s fun, maybe because I was curious to find out how much the workload differs between designers and coders, or maybe because I wanted an excuse to ignore the important delivery for the next day. Either way, it was wonderful to escape my responsibilities with this project.</p><h3>Design</h3><p>First of all, I promised myself to recreate the design in a slightly different way. That’s because doing a copy and paste of that stuff there would have falsified it. So I decided that the future component would have the features of the stock iOS toggle. Armed with Figma and patience, I stole a toggle from the usual UIKit component catalog and started populating it with clouds.</p><p>After an intense hour of work I get this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*2706aeNz6ayJxvkGrbY-5Q.png" /></figure><p>Not bad for a coder, right?</p><p>If you would like to know the tricks of the master you can find this component <a href="https://www.figma.com/community/file/1257854310310516832">here</a>.</p><h3>Code</h3><p>Having reached this point, I had to make a choice: export the images from Figma and use them in Xcode like a boy, or arm myself with holy patience and implement everything in SwiftUI like a man. Spoiler: I took a little from both. I developed pretty much everything in SwiftUI except for one thing: the background. I’m sorry but it was too articulate, from the clouds to the stars I should have hardcoded a lot of elements.</p><p>The code took me about an hour and a quarter, and the result was this:</p><pre>import SwiftUI<br><br>public struct SunToggleStyle: ToggleStyle {<br>    public func makeBody(configuration: Configuration) -&gt; some View {<br>        HStack() {<br>            if configuration.isOn {<br>                Spacer()<br>            }<br>            ZStack {<br>                Circle()<br>                if configuration.isOn {<br>                    moonseas.blendMode(.sourceAtop)<br>                }<br>            }.compositingGroup()<br>                .foregroundStyle(<br>                    (configuration.isOn ? Color.moon : .sun)<br>                        .gradient<br>                        .shadow(<br>                            .inner(<br>                                color: .black.opacity(0.15),<br>                                radius: 2,<br>                                x: -2,<br>                                y: -2<br>                            )<br>                        ).shadow(<br>                            .inner(<br>                                color: .white.opacity(0.50),<br>                                radius: 2,<br>                                x: 1,<br>                                y: 1<br>                            )<br>                        ).shadow(<br>                            .drop(<br>                                color: .black.opacity(0.06),<br>                                radius: 1,<br>                                x: 0,<br>                                y: 3<br>                            )<br>                        ).shadow(<br>                            .drop(<br>                                color: .black.opacity(0.15),<br>                                radius: 5,<br>                                x: 0,<br>                                y: 3<br>                            )<br>                        )<br>                )<br>                .background {<br>                    Circle()<br>                        .foregroundColor(.white.opacity(0.1))<br>                        .padding(-8)<br>                }<br>                .background {<br>                    Circle()<br>                        .foregroundColor(.white.opacity(0.1))<br>                        .padding(-16)<br>                }<br>            if !configuration.isOn {<br>                Spacer()<br>            }<br>        }<br>        .padding(2)<br>        .frame(width: 51, height: 31)<br>        .background(background(configuration))<br>        .onTapGesture {<br>            configuration.isOn.toggle()<br>        }<br>        .cornerRadius(30)<br>        .animation(<br>            .interpolatingSpring(stiffness: 300, damping: 20),<br>            value: configuration.isOn<br>        )<br>    }<br>    <br>    var moonseas: some View {<br>        ZStack(alignment: .center) {<br>            Circle()<br>                .offset(x: -4.5, y: 2.5)<br>                .frame(width: 8, height: 8)<br>            Circle()<br>                .frame(width: 4, height: 4)<br>                .offset(x: -0.5, y: -5.5)<br>            Circle()<br>                .frame(width: 5, height: 5)<br>                .offset(x: 6, y: 4)<br>        }.foregroundStyle(<br>            Color.moonsea<br>                .gradient<br>                .shadow(<br>                    .inner(<br>                        color: .black.opacity(0.25),<br>                        radius: 0.3,<br>                        x: 0,<br>                        y: 0.5<br>                    )<br>                )<br>        ).frame(width: 17, height: 15)<br>    }<br>    <br>    func background(_ configuration: Configuration) -&gt; some View {<br>        (configuration.isOn ? Color.night : .day)<br>            .animation(.linear(duration: 0.2), value: configuration.isOn)<br>            .overlay {<br>                Image(&quot;Background&quot;, bundle: .module)<br>                    .offset(x: 8.5, y: configuration.isOn ? 22.5 : -4.5)<br>            }<br>    }<br>    <br>    public init() { }<br>}</pre><p>You can find the code <a href="https://github.com/nunzioricci2000/SunToggle">here</a>. This repo is meant as a library so you can add it directly to your project. You can find the info about the installation directly in the readme of the repo.</p><h3>Unexpected retrospective</h3><p>Besides realizing that designers and coders have virtually no difference in the amount of work, this project has opened my eyes to a problem with SwiftUI. It could sound a bit technical, but if you have the patience to follow along you will see that it is actually quite limiting.</p><p>If you’ve been developing in SwiftUI for a while you’ve certainly used ButtonStyle. It’s handy for creating tap-responsive styles. This is because the makeBody method takes as input a Configuration object. This object provides a property called isPressed with which you can customize the behavior of the button on tap.</p><p>If you are a veteran you will also be familiar with another very useful protocol: PrimitiveButtonStyle. This allows you to remove the default behavior of a button and replace it with whatever you like (a use case might be, for example, creating a delete button that needs to be tapped twice before performing the action). The Configuration object that takes this makeBody method will no longer have the isPressed property but will have a method called trigger that will execute the button action.</p><p>Here’s the problem: In SwiftUI, button styles are the only ones that have this distinction. All other styles are handled as “Primitive” and therefore don’t embed the default logic of the corresponding stock components. Currently, the toggle I created, even if it looks like it, doesn’t behave perfectly like a native toggle, this is because the real behavior of the toggle is quite complex, and if you could enclose all this logic with a more specific protocol it would be possible to create components with an incredible consistency with the system.</p><p>I hope that in the next versions of SwiftUI, they think of a solution for this. In the meantime, I ask for your help. If you know of any library that solves this problem, let me know.</p><p>I wish you a good life and thank you for your attention. I hope I made you smile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aaded7ea06c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SwiftUI persistency wrappers through their procedural alternative]]></title>
            <link>https://medium.com/@nunzio.ricci.2000/understanding-swiftui-persistency-wrappers-through-their-procedural-alternative-b94c80434dd7?source=rss-eaadbb01d7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b94c80434dd7</guid>
            <category><![CDATA[apple-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Nunzio Ricci]]></dc:creator>
            <pubDate>Tue, 02 May 2023 12:46:38 GMT</pubDate>
            <atom:updated>2023-05-02T12:46:38.865Z</atom:updated>
            <content:encoded><![CDATA[<p>If you just started your journey with SwiftUI you must surely have seen stuff like @State, @StateObject, @AppStorage, @FetchRequest, etc. All of those are <strong>property wrappers</strong>. I highly suggest reading the Swift Documentation to know in depth what a property wrapper is, but it isn’t needed to read this guide. We will talk about @AppStorage and @FetchRequest, those are two wrappers that can read and save data from the stored memory, to understand them we’ll explore their procedural alternative to understand how they work under the hood.</p><h3>What does “Procedural alternative” mean?</h3><p>If you have ever programmed in other languages you know that if you want to get the program to draw something you will have to tell it something like:</p><pre>PutBrushAtPosition(200,200)<br>DrawLineTo(400,200)<br>DrawLineTo(300,400)<br>DrawLineTo(200,200)<br>AddSquareAt(500,500)<br>FillCircleAt(200,200)<br>PutTextIntCircleAt(200,200,&quot;I&#39;m a circle&quot;)</pre><p>You are writing a list of commands to be executed in order: a <strong>procedure</strong>. When you program something like that you have full control of the program but sometimes you risk forgetting what your code does.</p><pre>Canvas {<br>  Line(form: (200, 200), to: (400,200))<br>  Line(form: (400, 200), to: (300,400))<br>  Line(form: (300, 400), to: (200,200))<br>  Square(at: (500, 500))<br>  Circle(at: (200, 200))<br>    .fill()<br>    .innerText(&quot;I&#39;m a circle&quot;)<br>}</pre><p>In this example instead, we have a declarative way to write an equivalent program. The difference seems subtle but it is substantial. In the previous snippet, we are giving the PC the recipe to create the image that we want to show on the screen, in the second one we are only describing what we want to see without caring how it is calculated.</p><h3>@AppStorage and UserDefaults</h3><h4>What are UserDefaults?</h4><p><strong>UserDefaults</strong> are a really simple and useful way to quickly save a small amount of data on the storage. They are structured like a <strong>dictionary</strong>, you can save and load data using a <strong>key</strong>. For example, you can store the integer 10000 with the key &quot;score&quot; so that when you will ask for the value with that key UserDefaults will retrieve it until you change it. Let’s see how they work:</p><pre>UserDefaults.standard.set(10000, forKey: &quot;score&quot;)<br>let score = UserDefaults.standard.integer(forKey: &quot;score&quot;)</pre><p>This is the code for saving and loading 10000 with the key &quot;score&quot;. Let’s analyze a bit:</p><ol><li>UserDefaults is the class we interact with to use UserDefaults;</li><li>standard is an instance of UserDefaults. UserDefaults allows you to create your instances but for 99.9% of cases it is not needed;</li><li>set is the method by which you save all the data (integers, strings, raw binary…);</li><li>integer is the method by which you load integers. One such method exists for each type (ex.: string for strings, data for raw binary…).</li></ol><p>Ok all very cool, but what does it matter with AppStorage?</p><h4>What is AppStorage?</h4><p>AppStorage like any good property wrapper wraps a property… but what does that mean? A wrapper customizes access to a variable by running custom code each time you want to read or write the wrapped property.</p><p>Let’s look at these two snippets:</p><pre>var score: Int {<br>    get {<br>        UserDefaults.standard.integer(forKey: &quot;score&quot;)<br>    }<br>    nonmutating set {<br>        UserDefaults.standard.set(newValue, forKey: &quot;score&quot;)<br>    }<br>}</pre><pre>@AppStorage(&quot;score&quot;) var score: Int = 0</pre><p>These do almost the same thing. The exciting part in the second case is not so much that we are using less code, but that the code we are using is no longer a recipe for how to save the value in storage, rather we are declaring that this value is saved in storage without worrying about how. It is not a matter of saving time but of readability.</p><h4>How to use AppStorage</h4><p>Now that we understand how it works, let’s see how to use it.</p><pre>@AppStorage(&quot;score&quot;) var score: Int = 0<br>               1                 2    3</pre><ol><li>&quot;score&quot; is the key we want to access;</li><li>Int is the type of data we want to access;</li><li>0 is the default value for the variable that is automatically initialized with that value if nothing has been saved with this key yet.</li></ol><p>And that’s it! There is not much to add, these are the notions that will suffice for you in the vast majority of cases.</p><h3>@FetchRequest and CoreData</h3><p>CoreData is a powerful tool that allows you to store a large amount of data in tables. In this guide, I&#39;ll not explain much about CoreData because it is a huge topic, and I’m not qualified to speak about it. Instead, we will focus on an initial setup and how to integrate it into our SwiftUI apps.</p><h4>How CoreData works</h4><p>To put it simply, CoreData allows you to create tables called <strong>entities</strong> that represent the type of data that you want to save. To create these entities easily in your Xcode project, you can create a new file and choose as file type <em>Data Model</em>. To create a new entity you can find at the bottom slightly to the left a button called <em>Add Entity</em>, clicking on it you can see a new record in the sidebar called <em>Entity</em>. You can click on it and change his name how you want, I called it <em>User</em>. Selecting it now you can see three tables that you can fill. Today, we’ll speak only about the first one: <strong>attributes</strong>. In this table, you can add new attributes that will describe which simple data will compose the complex ones. To add one you can tap the <em>plus button</em> under the table and choose name and type. In our case, since I choose to describe a user I’ll add two attributes: <em>name</em> of type <em>String</em> and <em>passcode</em> of type <em>Integer 16</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xl_zwYP4F9Do00QJJ32i7w.jpeg" /><figcaption>If you’ve done all as me you should see something like that</figcaption></figure><p>By doing something like that we are creating a single table that looks like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ajqrwf8KA1u6swZ0xKv24g.png" /></figure><p>So how can I use it? To use this table you have to create an instance of NSPersistentContainer passing to it the name of the file containing the entities:</p><pre>let container = NSPersistentContainer(name: &quot;Model&quot;)</pre><p>To keep it simple this object wraps up all the persistence stuff that you need to interact with the storage. Inside it, there is a property called viewContext this object tracks all the interactions with the data and this is what we need to write and read on the persistent memory.</p><pre>let context = container.viewContext</pre><p>Now to save our first object we can do this:</p><pre>let user = User(context: context)<br>user.name = &quot;Ugo&quot;<br>user.passcode = 2222<br>try? context.save()</pre><p>When we create an instance of <em>User</em> passing the context, CoreData automatically sets this object as a new element of our table, and after filled we can save the context and this we’ll be saved on the storage. To retrieve all the data saved in the table as a list we’ll use the <em>fetch</em> method:</p><pre>try? context.fetch(NSFetchRequest(entityName: &quot;User&quot;)) as? [User]</pre><p>To edit an element of the table you can modify an element of the list and save the context:</p><pre>let users = try? context.fetch(NSFetchRequest(entityName: &quot;User&quot;)) as? [User]<br>let aUser = users?.first<br>aUser?.name = &quot;Flavio&quot;<br>try? context.save()</pre><p>Instead, to delete it you can use the delete method of the context:</p><pre>context.delete(aUser)<br>try? context.save()</pre><p>I know, there are a lot of things that seem to have no sense in this chapter but the reality is that CoreData is a really powerful tool that should be used for something way more complex than that.</p><p>At this point, I highly recommend doing some tests on your own to better understand how it works. For example, try to add some attributes or display data in SwiftUI.</p><h4>How @FetchRequest works</h4><p>In contrast to how AppStorage works, FetchRequest doesn’t write on the storage but reads only from it. Let’s make a comparison also here between FetchRequest and its procedural alternative:</p><pre>@Environment(\.managedObjectContext) private var viewContext<br>var users: [User]? {<br>    return try? context.fetch(NSFetchRequest(entityName: &quot;User&quot;)) as? [User]<br>}</pre><pre>@FetchRequest(fetchRequest: NSFetchRequest(entityName: &quot;User&quot;)) <br>var users: FetchedResults&lt;User&gt;</pre><p>Also here we have two snippets that have a similar result. As you can see in the first one you have to retrieve the environment value managedObjectContext because that is exactly what FetchRequest does, so is a good practice to pass it as soon as possible in the hierarchy of the views. Here we have an example:</p><pre>import SwiftUI<br>import CoreData<br><br>@main<br>struct TutorialApp: App {<br>    let container = NSPersistentContainer(name: &quot;Model&quot;)<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(\.managedObjectContext, container.viewContext)<br>        }<br>    }<br>}</pre><p>For now, it’s all. I hope that this guide helped you to better understand the behaviors of SwiftUI under the hood. See you soon in the next guide!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b94c80434dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom iOS keyboard using SwiftUI]]></title>
            <link>https://medium.com/@nunzio.ricci.2000/create-a-custom-ios-keyboard-using-swiftui-4e4e854365ef?source=rss-eaadbb01d7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4e854365ef</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[custom-keyboard]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Nunzio Ricci]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 05:06:17 GMT</pubDate>
            <atom:updated>2023-02-27T05:06:17.714Z</atom:updated>
            <content:encoded><![CDATA[<p>Very often when it comes to iOS development, we sadly come across procedures that necessarily require the use of UIKit. Fortunately, today I want to introduce you to the way I avoided this problem.</p><h3>Creating the project</h3><p>First of all, you have to create a new project. We’ll create an iOS application. Once the app has been created we can proceed in the following way:</p><ol><li>In Xcode, click on the project folder</li><li>Then click on the plus sign under “Targets”</li><li>Select “Custom Keyboard Extention”</li><li>And give it a name.</li></ol><h3>Creating the keyboard</h3><p>If you want, at this point you can try to build your app on an iPhone to see if the keyboard works. To do it you need to go into the settings of the device and add your new keyboard to your actual keyboards list.</p><p>Now you have a new group containing two files, one is “Info.plist” and the other is “KeyboardViewController.swift”. This last is the interesting one. Opening it you’ll find this code:</p><pre>import UIKit<br><br>class KeyboardViewController: UIInputViewController {<br>    @IBOutlet var nextKeyboardButton: UIButton!<br>    <br>    override func updateViewConstraints() {<br>        super.updateViewConstraints()<br>        <br>        // Add custom view sizing constraints here<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // Perform custom UI setup here<br>        self.nextKeyboardButton = UIButton(type: .system)<br>        <br>        self.nextKeyboardButton.setTitle(NSLocalizedString(&quot;Next Keyboard&quot;, comment: &quot;Title for &#39;Next Keyboard&#39; button&quot;), for: [])<br>        self.nextKeyboardButton.sizeToFit()<br>        self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false<br>        <br>        self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)<br>        <br>        self.view.addSubview(self.nextKeyboardButton)<br>        <br>        self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true<br>        self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true<br>    }<br>    <br>    override func viewWillLayoutSubviews() {<br>        self.nextKeyboardButton.isHidden = !self.needsInputModeSwitchKey<br>        super.viewWillLayoutSubviews()<br>    }<br>    <br>    override func textWillChange(_ textInput: UITextInput?) {<br>        // The app is about to change the document&#39;s contents. Perform any preparation here.<br>    }<br>    <br>    override func textDidChange(_ textInput: UITextInput?) {<br>        // The app has just changed the document&#39;s contents, the document context has been updated.<br>        <br>        var textColor: UIColor<br>        let proxy = self.textDocumentProxy<br>        if proxy.keyboardAppearance == UIKeyboardAppearance.dark {<br>            textColor = UIColor.white<br>        } else {<br>            textColor = UIColor.black<br>        }<br>        self.nextKeyboardButton.setTitleColor(textColor, for: [])<br>    }<br>}</pre><p>Now we want to create a SwiftUI view that will be our custom keyboard:</p><pre>import SwiftUI<br><br>struct Keyboard: View {<br>    var body: some View {<br>        Button(&quot;Hello, Keyboard!&quot;) { }<br>    }<br>}</pre><p>Now we need to integrate this view in the <em>KeyboardViewController</em>. First of all, we need to import SwiftUI also in this file. Next, we’ll copy this snippet of code <em>viewDidLoad</em> method:</p><pre>let keyboardController = UIHostingController(rootView: Keyboard())<br>let keyboardView = keyboardController.view!<br>keyboardView.translatesAutoresizingMaskIntoConstraints = false<br>keyboardView.backgroundColor = .clear<br>addChild(keyboardController)<br>view.addSubview(keyboardView)<br>NSLayoutConstraint.activate([<br>    keyboardView.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>    keyboardView.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>])<br>keyboardController.didMove(toParent: self)</pre><p>I strongly suggest reading the guide in the following link to know more about this implementation: <a href="https://sarunw.com/posts/swiftui-view-as-uiview/">https://sarunw.com/posts/swiftui-view-as-uiview/</a>.</p><p>Okay now we have the keyboard… but how do we write?</p><h3>Writing and deleting</h3><p>First of all, we need a crucial object from our <em>KeyboardViewController</em>: the <em>textDocumentProxy</em>. In our SwiftUI view, we’ll declare a new property to receive our special object:</p><pre>import SwiftUI<br><br>struct Keyboard: View {<br>    @State var proxy: UITextDocumentProxy<br>    <br>    var body: some View {<br>        Button(&quot;Hello, Keyboard!&quot;) { }<br>    }<br>}</pre><p>And in <em>KeyboardViewController</em> we change the Keyboard view initialization with:</p><pre>let keyboardController = UIHostingController(rootView: Keyboard(proxy: self.textDocumentProxy))</pre><p>And the magic is done!</p><p>We just have to see how to use it within our view. <em>UITextDocumentProxy</em> protocol provides an <em>insertText</em> method that is really easy to use.</p><pre>import SwiftUI<br><br>struct Keyboard: View {<br>    @State var proxy: UITextDocumentProxy<br>    <br>    var body: some View {<br>        Button(&quot;Hello, Keyboard!&quot;) {<br>            proxy.insertText(&quot;hello&quot;)<br>        }<br>    }<br>}</pre><p>With this, we’ve created a new keyboard that has only one button that types “hello”.</p><p>We can add also a delete button with the <em>deleteBackward</em> method:</p><pre>import SwiftUI<br><br>struct Keyboard: View {<br>    @State var proxy: UITextDocumentProxy<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Hello, Keyboard!&quot;) {<br>                proxy.insertText(&quot;hello&quot;)<br>            }<br>            Button(&quot;Delete&quot;) {<br>                proxy.deleteBackward()<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5RXAtlzZBMIuizBdVHyQw.jpeg" /></figure><p>This is the final result. I remind you that in order to see the new keyboard you must first add it to the iPhone settings.</p><p>I hope this article may have been helpful to you, See you in the next guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4e854365ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>