<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SwiftUI Tutorials - AppMakers.Dev</title>
	<atom:link href="https://appmakers.dev/category/swiftui/swiftui-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>https://appmakers.dev/category/swiftui/swiftui-tutorials/</link>
	<description>SwiftUI Tutorials, iOS App Development, SwiftUI, Swift</description>
	<lastBuildDate>Tue, 10 Jun 2025 11:35:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://appmakers.dev/wp-content/uploads/2024/10/cropped-AppMakersDev-32x32.jpg</url>
	<title>SwiftUI Tutorials - AppMakers.Dev</title>
	<link>https://appmakers.dev/category/swiftui/swiftui-tutorials/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Build Your First Widget in SwiftUI — A Guide with Source Code</title>
		<link>https://appmakers.dev/build-your-first-widget-in-swiftui-a-guide-with-source-code/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Mon, 09 Jun 2025 21:17:47 +0000</pubDate>
				<category><![CDATA[iOS Development]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<category><![CDATA[SwiftUI Widgets]]></category>
		<guid isPermaLink="false">https://appmakers.dev/?p=1985</guid>

					<description><![CDATA[<p>Want to bring widgets to your SwiftUI app but not sure where to begin? This updated tutorial walks you through the entire process of creating a SwiftUI Widget using WidgetKit, complete with step-by-step guidance and working code. By the end, you’ll have a motivational widget that refreshes every 10 minutes with custom colors and messages.&#8230;</p>
<p>The post <a href="https://appmakers.dev/build-your-first-widget-in-swiftui-a-guide-with-source-code/">Build Your First Widget in SwiftUI — A Guide with Source Code</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Want to bring widgets to your SwiftUI app but not sure where to begin? This updated tutorial walks you through the entire process of creating a SwiftUI Widget using WidgetKit, complete with step-by-step guidance and working code. By the end, you’ll have a motivational widget that refreshes every 10 minutes with custom colors and messages.</p>
<p><a href="https://appmakers.gumroad.com/l/swiftui-widget-basic">🔗 <strong data-start="9287" data-end="9330">Download the full commented source code (Xcode Project) for this Tutorial</strong></a></p>
<h2 data-start="688" data-end="742">🧰 Getting Started — Create a Fresh SwiftUI Project</h2>
<p data-start="744" data-end="775">Open Xcode and start a new app:</p>
<ul data-start="777" data-end="903">
<li data-start="777" data-end="815">
<p data-start="779" data-end="815">Go to <strong data-start="785" data-end="815">File → New → Project → App</strong></p>
</li>
<li data-start="816" data-end="862">
<p data-start="818" data-end="862">Name your project something like <code class="" data-line="">WidgetApp</code></p>
</li>
<li data-start="863" data-end="885">
<p data-start="865" data-end="885">Interface: SwiftUI</p>
</li>
<li data-start="886" data-end="903">
<p data-start="888" data-end="903">Language: Swift</p>
</li>
</ul>
<p data-start="905" data-end="951">Save the project and move on to the next step.</p>
<h2 data-start="958" data-end="987">➕ Add the Widget Extension</h2>
<p data-start="989" data-end="1026">Now it’s time to add a widget target:</p>
<ul data-start="1028" data-end="1259">
<li data-start="1028" data-end="1053">
<p data-start="1030" data-end="1053"><strong data-start="1030" data-end="1053">File → New → Target</strong></p>
</li>
<li data-start="1054" data-end="1083">
<p data-start="1056" data-end="1083">Select <strong data-start="1063" data-end="1083">Widget Extension</strong></p>
</li>
<li data-start="1084" data-end="1165">
<p data-start="1086" data-end="1106">Uncheck the options:</p>
<ul data-start="1109" data-end="1165">
<li data-start="1109" data-end="1124">
<p data-start="1111" data-end="1124">Live Activity</p>
</li>
<li data-start="1127" data-end="1136">
<p data-start="1129" data-end="1136">Control</p>
</li>
<li data-start="1139" data-end="1165">
<p data-start="1141" data-end="1165">Configuration App Intent</p>
</li>
</ul>
</li>
<li data-start="1166" data-end="1208">
<p data-start="1168" data-end="1208">Name it something like <code class="" data-line="">WidgetAppWidget</code></p>
</li>
<li data-start="1209" data-end="1259">
<p data-start="1211" data-end="1259">Confirm and activate the new scheme if prompted.</p>
</li>
</ul>
<h2 data-start="1266" data-end="1307">🔍 Understand the Auto-Generated Files</h2>
<p data-start="1309" data-end="1341">Xcode will create two key files:</p>
<h3 data-start="1343" data-end="1384"><code class="" data-line="">AppWidgetBundle.swift</code> – Entry Point</h3>
<p data-start="1386" data-end="1461">This struct defines your widget bundle and serves as the extension&#8217;s entry:</p>
<pre><code class="language-swift" data-line="">import WidgetKit
import SwiftUI

@main
struct AppWidgetBundle: WidgetBundle {
    var body: some Widget {
        AppWidget()
    }
}</code></pre>
<div class="contain-inline-size rounded-2xl border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"></div>
<ul data-start="1635" data-end="1791">
<li data-start="1635" data-end="1722">
<p data-start="1637" data-end="1722">The <code class="" data-line="">@main</code> attribute designates this as the starting point of your widget extension.</p>
</li>
<li data-start="1723" data-end="1791">
<p data-start="1725" data-end="1791">You can group multiple widgets into this bundle in future updates.</p>
</li>
</ul>
<h3 data-start="1798" data-end="1842"><code class="" data-line="">AppWidget.swift</code> – The Core Widget File</h3>
<p data-start="1844" data-end="1892">This file contains everything your widget needs:</p>
<ul data-start="1893" data-end="2076">
<li data-start="1893" data-end="1927">
<p data-start="1895" data-end="1927">A <strong data-start="1897" data-end="1911">data model</strong> (<code class="" data-line="">SimpleEntry</code>)</p>
</li>
<li data-start="1928" data-end="1953">
<p data-start="1930" data-end="1953">A <strong data-start="1932" data-end="1953">timeline provider</strong></p>
</li>
<li data-start="1954" data-end="1984">
<p data-start="1956" data-end="1984">A <strong data-start="1958" data-end="1984">view for the widget UI</strong></p>
</li>
<li data-start="1985" data-end="2034">
<p data-start="1987" data-end="2034">The actual <strong data-start="1998" data-end="2015">widget struct</strong> with configuration</p>
</li>
<li data-start="2035" data-end="2076">
<p data-start="2037" data-end="2076">A <strong data-start="2039" data-end="2051">#Preview</strong> section to test in Xcode</p>
</li>
</ul>
<h2 data-start="2083" data-end="2122">📦 1. Define the Widget’s Data Model</h2>
<p data-start="2124" data-end="2202">The <code class="" data-line="">SimpleEntry</code> struct represents the snapshot of data shown at each update:</p>
<pre><code class="language-swift" data-line="">struct SimpleEntry: TimelineEntry {
    let date: Date
    let emoji: String
}
</code></pre>
<ul>
<li data-start="2297" data-end="2348">
<p data-start="2299" data-end="2348"><code class="" data-line="">date</code>: Tells the system when to show this entry.</p>
</li>
<li data-start="2349" data-end="2448">
<p data-start="2351" data-end="2448"><code class="" data-line="">emoji</code>: Temporary example content — later, we’ll replace it with a message and background color.</p>
</li>
</ul>
<h2 data-start="2455" data-end="2494">🧠 2. Implement the TimelineProvider</h2>
<p data-start="2496" data-end="2594">The <code class="" data-line="">TimelineProvider</code> tells WidgetKit what to display and when. It includes three main functions:</p>
<pre><code class="language-swift" data-line="">struct Provider: TimelineProvider {
   // 1️⃣ func placeholder(in context: Context) -&gt; SimpleEntry { … }
   // 2️⃣ func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -&gt; ()) { … }
   // 3️⃣ func getTimeline(in context: Context, completion: @escaping (Timeline&lt;SimpleEntry&gt;) -&gt; ()) { … }
}
</code></pre>
<h3 data-start="2921" data-end="2947">1️⃣ <code class="" data-line="">placeholder(in:)</code></h3>
<p data-start="2948" data-end="2994">Shows temporary content in the widget gallery.</p>
<pre><code class="language-swift" data-line="">func placeholder(in context: Context) -&gt; SimpleEntry {
    SimpleEntry(date: Date(), emoji: &quot;😀&quot;)
}
</code></pre>
<h3 data-start="3110" data-end="3136">2️⃣ <code class="" data-line="">getSnapshot(in:)</code></h3>
<p data-start="3137" data-end="3172">Provides a static snapshot of data.</p>
<pre><code class="language-swift" data-line="">func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -&gt; ()) {
    let entry = SimpleEntry(date: Date(), emoji: &quot;😀&quot;)
    completion(entry)
}
</code></pre>
<h3 data-start="3350" data-end="3376">3️⃣ <code class="" data-line="">getTimeline(in:)</code></h3>
<p data-start="3377" data-end="3414">Generates a list of timeline entries.</p>
<pre><code class="language-swift" data-line="">func getTimeline(in context: Context, completion: @escaping (Timeline&lt;Entry&gt;) -&gt; ()) {
    var entries: [SimpleEntry] = []

    let currentDate = Date()
    for hourOffset in 0 ..&lt; 5 {
        let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
        let entry = SimpleEntry(date: entryDate, emoji: &quot;😀&quot;)
        entries.append(entry)
    }

    let timeline = Timeline(entries: entries, policy: .atEnd)
    completion(timeline)
}
</code></pre>
<h2 data-start="3908" data-end="3951">🖼️ 3. Create the Widget UI with SwiftUI</h2>
<p data-start="3953" data-end="4018">Use SwiftUI to define how your widget appears on the home screen.</p>
<pre><code class="language-swift" data-line="">struct AppWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        VStack {
            Text(&quot;Time:&quot;)
            Text(entry.date, style: .time)
            Text(&quot;Emoji:&quot;)
            Text(entry.emoji)
        }
    }
}
</code></pre>
<h2 data-start="4292" data-end="4331">🧱 4. Configure the Widget Structure</h2>
<p data-start="4333" data-end="4405">This section ties everything together and registers the widget with iOS.</p>
<pre><code class="language-swift" data-line="">struct AppWidget: Widget {
    let kind: String = &quot;AppWidget&quot;

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            if #available(iOS 17.0, *) {
                AppWidgetEntryView(entry: entry)
                    .containerBackground(.fill.tertiary, for: .widget)
            } else {
                AppWidgetEntryView(entry: entry)
                    .padding()
                    .background()
            }
        }
        .configurationDisplayName(&quot;My Widget&quot;)
        .description(&quot;This is an example widget.&quot;)
    }
}
</code></pre>
<h2 data-start="5029" data-end="5060">👀 5. Previewing Your Widget</h2>
<p data-start="5062" data-end="5125">SwiftUI’s new <code class="" data-line="">#Preview</code> lets you simulate the widget in Xcode.</p>
<pre><code class="language-swift" data-line="">#Preview(as: .systemSmall) {
    AppWidget()
} timeline: {
    SimpleEntry(date: .now, emoji: &quot;😀&quot;)
    SimpleEntry(date: .now, emoji: &quot;🤩&quot;)
}
</code></pre>
<h2 data-start="5289" data-end="5343">🎯 Make It Useful — Show Random Motivational Quotes</h2>
<p data-start="5345" data-end="5383">Let’s make this widget more inspiring.</p>
<p data-start="5385" data-end="5483">Instead of an emoji, we’ll show motivational quotes every 10 minutes and change background colors.</p>
<p data-start="5385" data-end="5483">🛠 Update SimpleEntry</p>
<pre><code class="language-swift" data-line="">struct SimpleEntry: TimelineEntry {
    let date: Date
    let message: String
    let color: Color
}
</code></pre>
<h3 data-start="5638" data-end="5660">🧠 Update Provider</h3>
<p data-start="5662" data-end="5693">Add sample messages and colors:</p>
<pre><code class="language-swift" data-line="">let messages = [
    &quot;Keep going 💪&quot;, &quot;You&#039;re doing great!&quot;, &quot;Just one more step 🚶&quot;,
    &quot;Stay focused 🎯&quot;, &quot;You’ve got this 🔥&quot;, &quot;Make it count 💥&quot;,
    &quot;Smile, breathe, move 🌿&quot;, &quot;Every moment matters ⏳&quot;
]

let backgroundColors: [Color] = [
    .blue, .green, .orange, .pink, .purple, .yellow, .teal, .mint
]

let defaultColor: Color = .gray
let defaultMessage = &quot;Keep going 💪&quot;
</code></pre>
<p>Update <code class="" data-line="">placeholder</code> and <code class="" data-line="">getSnapshot</code>:</p>
<pre><code class="language-swift" data-line="">func placeholder(in context: Context) -&gt; SimpleEntry {
    SimpleEntry(date: Date(), message: defaultMessage, color: defaultColor)
}

func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -&gt; ()) {
    let entry = SimpleEntry(date: Date(), message: defaultMessage, color: defaultColor)
    completion(entry)
}
</code></pre>
<p>Update <code class="" data-line="">getTimeline</code>:</p>
<pre><code class="language-swift" data-line="">func getTimeline(in context: Context, completion: @escaping (Timeline&lt;Entry&gt;) -&gt; ()) {
    var entries: [SimpleEntry] = []
    let currentDate = Date()

    for minuteOffset in 0 ..&lt; 6 {
        let entryDate = Calendar.current.date(byAdding: .minute, value: minuteOffset * 10, to: currentDate)!
        let message = messages.randomElement() ?? defaultMessage
        let backgroundColor = backgroundColors.randomElement() ?? defaultColor
        let entry = SimpleEntry(date: entryDate, message: message, color: backgroundColor)
        entries.append(entry)
    }

    let timeline = Timeline(entries: entries, policy: .atEnd)
    completion(timeline)
}
</code></pre>
<p>🎨 Redesign the Widget View</p>
<pre><code class="language-swift" data-line="">struct AppWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        ZStack {
            VStack(spacing: 10) {
                Text(entry.message)
                    .font(.headline)
                    .multilineTextAlignment(.center)
                    .minimumScaleFactor(0.5)
                    .lineLimit(1)
                    .foregroundStyle(.primary)

                Text(entry.date, style: .time)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
    }
}
</code></pre>
<p>⚙️ Update Widget Config</p>
<pre><code class="language-swift" data-line="">struct AppWidget: Widget {
    let kind: String = &quot;AppWidget&quot;

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            let backgroundColor = entry.color.opacity(0.25)

            if #available(iOS 17.0, *) {
                AppWidgetEntryView(entry: entry)
                    .containerBackground(backgroundColor, for: .widget)
            } else {
                AppWidgetEntryView(entry: entry)
                    .padding()
                    .background(backgroundColor)
            }
        }
        .configurationDisplayName(&quot;Motivational Widget&quot;)
        .description(&quot;This Widget Will Keep You Motivated&quot;)
    }
}
</code></pre>
<p>🧪 Preview It</p>
<pre><code class="language-swift" data-line="">#Preview(&quot;Small Widget&quot;, as: .systemSmall) {
    AppWidget()
} timeline: {
    SimpleEntry(date: .now, message: &quot;Keep going 💪&quot;, color: .orange)
    SimpleEntry(date: .now, message: &quot;Stay focused 🎯&quot;, color: .purple)
}
</code></pre>
<h2 data-start="8790" data-end="8817">📱 Test on a Real Device</h2>
<ol data-start="8819" data-end="9001">
<li data-start="8819" data-end="8868">
<p data-start="8822" data-end="8868">Run your <strong data-start="8831" data-end="8850">main app target</strong> on a real device.</p>
</li>
<li data-start="8869" data-end="8940">
<p data-start="8872" data-end="8940">Long-press the Home Screen → Tap &#8220;+&#8221; → Search for your widget → Add.</p>
</li>
<li data-start="8941" data-end="9001">
<p data-start="8944" data-end="9001">Optionally tap and <strong data-start="8963" data-end="8982">edit the widget</strong> for configuration.</p>
</li>
</ol>
<p data-start="9003" data-end="9090"><strong data-start="9003" data-end="9011">Note</strong>: App Groups aren’t required if your widget shows static or internal data only.</p>
<h2 data-start="9097" data-end="9113">✅ Final Notes</h2>
<ul data-start="9115" data-end="9282">
<li data-start="9115" data-end="9176">
<p data-start="9117" data-end="9176">Code is tested on Xcode 16.2 and iOS 18.2 (as of June 2025)</p>
</li>
<li data-start="9177" data-end="9231">
<p data-start="9179" data-end="9231">Always check compatibility with newer Xcode versions</p>
</li>
<li data-start="9232" data-end="9282">
<p data-start="9234" data-end="9282">If you run into issues, let us know via comments</p>
</li>
</ul>
<p><a href="https://appmakers.gumroad.com/l/swiftui-widget-basic">DOWNLOAD SOURCE CODE FOR THIS TUTORIAL</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://appmakers.dev/build-your-first-widget-in-swiftui-a-guide-with-source-code/">Build Your First Widget in SwiftUI — A Guide with Source Code</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Learn how to work with Xcode Previews in SwiftData App</title>
		<link>https://appmakers.dev/learn-how-to-work-with-xcode-previews-in-swiftdata-app/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Wed, 16 Oct 2024 11:30:05 +0000</pubDate>
				<category><![CDATA[iOS Development]]></category>
		<category><![CDATA[SwiftData]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Data and Storage]]></category>
		<category><![CDATA[SwiftUI State Management and Data Flow]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://appmakers.dev/?p=1776</guid>

					<description><![CDATA[<p>Learn how to work with Xcode Previews in SwiftData App. SwiftData in combination with SwiftUI allows you to quickly prototype and develop apps by providing easy-to-use, in-memory storage for model data. In this tutorial, we’ll walk through how to create sample recipe data using ModelContainer and display that data in SwiftUI views with previews. Step&#8230;</p>
<p>The post <a href="https://appmakers.dev/learn-how-to-work-with-xcode-previews-in-swiftdata-app/">Learn how to work with Xcode Previews in SwiftData App</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Learn how to work with Xcode Previews in SwiftData App</strong>. SwiftData in combination with SwiftUI allows you to quickly prototype and develop apps by providing easy-to-use, in-memory storage for model data. In this tutorial, we’ll walk through how to create sample recipe data using <code class="" data-line="">ModelContainer</code> and display that data in SwiftUI views with previews.</p>
<h3>Step 1: Defining the <code class="" data-line="">Recipe</code> Model</h3>
<p>Setup a <code class="" data-line="">Recipe</code> model that represents a dish with a name, cooking time, and ingredients.</p>
<pre><code class="language-swift" data-line="">import Foundation
import SwiftData

@Model
class Recipe {

    @Attribute(.unique) var id: UUID
    var name: String?
    var cookingTime: Int // in minutes
    var ingredients: [String]

    init(id: UUID = UUID(), name: String? = nil, cookingTime: Int, ingredients: [String]) {
        self.id = id
        self.name = name
        self.cookingTime = cookingTime
        self.ingredients = ingredients
    }
}
</code></pre>
<p>This model defines each recipe with a unique ID, name, cooking time, and a list of ingredients. With this setup, you can now store recipes in SwiftData and use them in your app.</p>
<h3>Step 2: Creating Sample Data for Previews</h3>
<p>Now, let’s generate sample data using <code class="" data-line="">ModelContainer</code>. You’ve written a method to insert sample recipes into a <code class="" data-line="">ModelContainer</code> for use in previews.</p>
<pre><code class="language-swift" data-line="">import Foundation
import SwiftData

let sampleRecipes = [
    Recipe(name: &quot;Spaghetti Bolognese&quot;, cookingTime: 45, ingredients: [&quot;Spaghetti&quot;, &quot;Minced Beef&quot;, &quot;Tomato Sauce&quot;]),
    Recipe(name: &quot;Grilled Cheese Sandwich&quot;, cookingTime: 10, ingredients: [&quot;Bread&quot;, &quot;Cheese&quot;, &quot;Butter&quot;]),
    Recipe(name: &quot;Beef Wellington&quot;, cookingTime: 120, ingredients: [&quot;Beef Tenderloin&quot;, &quot;Puff Pastry&quot;, &quot;Mushrooms&quot;, &quot;Dijon Mustard&quot;])
]

extension Recipe {
    @MainActor static func makeSampleRecipes(in container: ModelContainer) {
        
        let context = container.mainContext
        
        // Check if there are any existing recipes in the database
           let existingRecipesCount = (try? context.fetch(FetchDescriptor()))?.count ?? 0
           guard existingRecipesCount == 0 else {
               // If there are existing recipes, do not create new ones
               return
           }
           
           // Sample data to create
           let recipes = [
               Recipe(name: &quot;Spaghetti Bolognese&quot;, cookingTime: 45, ingredients: [&quot;Spaghetti&quot;, &quot;Minced Beef&quot;, &quot;Tomato Sauce&quot;]),
               Recipe(name: &quot;Grilled Cheese Sandwich&quot;, cookingTime: 10, ingredients: [&quot;Bread&quot;, &quot;Cheese&quot;, &quot;Butter&quot;]),
               Recipe(name: &quot;Beef Wellington&quot;, cookingTime: 120, ingredients: [&quot;Beef Tenderloin&quot;, &quot;Puff Pastry&quot;, &quot;Mushrooms&quot;, &quot;Dijon Mustard&quot;])
           ]
           
           // Insert the sample recipes into the context
           for recipe in recipes {
               context.insert(recipe)
           }
           
           // Save the context to persist the new data
           try? context.save()
        
    }
}

</code></pre>
<p>This method defines three recipes and inserts them into the <code class="" data-line="">ModelContainer</code>. The <code class="" data-line="">@MainActor</code> annotation ensures this method runs on the main thread, which is essential for interacting with SwiftData.</p>
<h3>Step 3: Implementing the <code class="" data-line="">RecipeSampleData</code> for Previews</h3>
<p><span id="more-1776"></span><br />
The <code class="" data-line="">RecipeSampleData</code> structure serves as a <code class="" data-line="">PreviewModifier</code> to create in-memory sample data. This makes it easy to display recipes in SwiftUI previews.</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct RecipeSampleData: PreviewModifier {
    static func makeSharedContext() throws -&gt; ModelContainer {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: Recipe.self, configurations: config)
        Recipe.makeSampleRecipes(in: container) // Load sample recipes
        return container
    }
    
    func body(content: Content, context: ModelContainer) -&gt; some View {
        content.modelContainer(context)
    }
}

extension PreviewTrait where T == Preview.ViewTraits {
    @MainActor static var sampleRecipeData: Self = .modifier(RecipeSampleData())
}
</code></pre>
<p>This modifier creates a <code class="" data-line="">ModelContainer</code> configured for in-memory storage. The <code class="" data-line="">makeSampleRecipes</code> method loads sample recipes into the container, and the modifier applies this data to any view using the <code class="" data-line="">.modelContainer()</code> modifier.</p>
<h3>Step 4: Creating Recipe Views with Sample Data</h3>
<p>Now let’s integrate this sample data into a few SwiftUI views.</p>
<h4>Recipe List View</h4>
<p>The <code class="" data-line="">RecipeListView</code> displays a list of recipes loaded from SwiftData. The <code class="" data-line="">@Query</code> property wrapper retrieves the recipes, and the list is built dynamically.</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct RecipeListView: View {
    @Query private var recipies: [Recipe]
    @Environment(\.modelContext) private var context
    
    var body: some View {
       
        List {
            ForEach(recipies) { recipe in
              
                VStack(alignment: .leading) {
                    Text(recipe.name ?? &quot;&quot;)
                           .font(.headline)
                       Text(&quot;Cooking Time: \(recipe.cookingTime) mins&quot;)
                           .font(.subheadline)
                   }
            }
        } .task {
            
               Recipe.makeSampleRecipes(in: context.container)
        }
    }
}

#Preview(traits: .sampleRecipeData) {
    RecipeListView()
}
</code></pre>
<p>In this example, the <code class="" data-line="">@Query</code> property wrapper retrieves all <code class="" data-line="">Recipe</code> objects from the <code class="" data-line="">ModelContainer</code>, which are then displayed in a <code class="" data-line="">List</code> using SwiftUI. The preview uses <code class="" data-line="">.sampleRecipeData</code> to load in-memory recipes for testing the UI.</p>
<h4>Recipe Detail View</h4>
<p>For more detailed recipe information, the <code class="" data-line="">RecipeDetailView</code> displays the name, cooking time, and ingredients of a single recipe. This view doesn’t query for data but accepts a <code class="" data-line="">Recipe</code> object as a parameter.</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct RecipeDetailView: View {
    let recipe: Recipe

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text(recipe.name ?? &quot;No Name&quot;)
                .font(.largeTitle)
            Text(&quot;Cooking Time: \(recipe.cookingTime) mins&quot;)
                .padding(.bottom)
            Text(&quot;Ingredients:&quot;)
            ForEach(recipe.ingredients, id: \.self) { ingredient in
                Text(ingredient)
            }
        }
        .padding()
    }
}

#Preview(traits: .sampleRecipeData) {
    @Previewable @Query var recipes: [Recipe]  // Query sample recipes
    RecipeDetailView(recipe: recipes.first!)
}
</code></pre>
<p>In this view, the recipe&#8217;s details are displayed, including the name, cooking time, and ingredients. The preview fetches the first recipe from the sample data.</p>
<h3>Step 5</h3>
<p>Now let&#8217;s connect our ListView with a DetailView using a NavigationLink inside a NavigationStack</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct RecipeListView: View {
    @Query private var recipies: [Recipe]
    @Environment(\.modelContext) private var context
    
    var body: some View {
       
        NavigationStack {
            List {
                ForEach(recipies) { recipe in
                    NavigationLink(destination: RecipeDetailView(recipe: recipe)) {
                        
                        // Recipe Row
                        VStack(alignment: .leading) {
                            Text(recipe.name ?? &quot;&quot;)
                                .font(.headline)
                            Text(&quot;Cooking Time: \(recipe.cookingTime) mins&quot;)
                                .font(.subheadline)
                        }
                    }
                }
            } .task {
                
                Recipe.makeSampleRecipes(in: context.container)
                
            }
        }
    }
}

#Preview(traits: .sampleRecipeData) {
    RecipeListView()
}</code></pre>
<h3>Key Differences Between <code class="" data-line="">Preview</code> and <code class="" data-line="">@Previewable</code></h3>
<ol>
<li><strong><code class="" data-line="">Preview</code> with Traits (<code class="" data-line="">.sampleRecipeData</code>)</strong>:
<ul>
<li>Best for views that query data using SwiftData.</li>
<li>Automatically loads sample data into the view’s query and binds it to the UI.</li>
<li>No need to manually pass data; the query handles it for you.</li>
</ul>
</li>
<li><strong><code class="" data-line="">@Previewable</code></strong>:
<ul>
<li>Best for views that rely on models passed in as parameters (e.g., detail views).</li>
<li>Allows you to create sample data and pass it directly to the view.</li>
<li>You have full control over what specific data is provided for the preview.</li>
</ul>
</li>
</ol>
<h3>Conclusion</h3>
<p>By using <code class="" data-line="">SampleData</code> and the <code class="" data-line="">@Previewable</code> macro, you can easily preview recipe data within your SwiftUI views. Whether you’re working with data that relies on queries or views that require individual models, SwiftData provides an efficient way to prototype and test your app in Xcode.</p>
<p>The post <a href="https://appmakers.dev/learn-how-to-work-with-xcode-previews-in-swiftdata-app/">Learn how to work with Xcode Previews in SwiftData App</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to display sample SwiftData in SwiftUI with PreviewModifier</title>
		<link>https://appmakers.dev/how-to-display-sample-swiftdata-in-swiftui-with-previewmodifier/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Sun, 13 Oct 2024 20:28:51 +0000</pubDate>
				<category><![CDATA[SwiftData]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Data and Storage]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://appmakers.dev/?p=1765</guid>

					<description><![CDATA[<p>In this tutorial, we will explore how to display sample SwiftData in SwiftUI with PreviewModifier Step 1: Define the Entity First, we need to define a Task entity that we will use to store our task data in SwiftData. import Foundation import SwiftData @Model class Task { @Attribute(.unique) var id: UUID var title: String? var isCompleted:&#8230;</p>
<p>The post <a href="https://appmakers.dev/how-to-display-sample-swiftdata-in-swiftui-with-previewmodifier/">How to display sample SwiftData in SwiftUI with PreviewModifier</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we will explore how to display sample SwiftData in SwiftUI with PreviewModifier</p>
<h2>Step 1: Define the Entity</h2>
<p>First, we need to define a <code class="" data-line="">Task</code> entity that we will use to store our task data in SwiftData.</p>
<pre><code class="language-swift" data-line="">import Foundation
import SwiftData

@Model
class Task {
    @Attribute(.unique) var id: UUID
    var title: String?
    var isCompleted: Bool

    init(id: UUID = UUID(), title: String? = nil, isCompleted: Bool = false) {
        self.id = id
        self.title = title
        self.isCompleted = isCompleted
    }
}
</code></pre>
<p>In this code, we define the <code class="" data-line="">Task</code> model with an <code class="" data-line="">id</code>, <code class="" data-line="">title</code>, and <code class="" data-line="">isCompleted</code> property. The <code class="" data-line="">@Model</code> attribute is used to make this class a SwiftData model.</p>
<h2>Step 2: Create the Task List View</h2>
<p>Next, we&#8217;ll create a SwiftUI view that displays a list of tasks, each with a toggle for marking them as completed or not.</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct TaskListView: View {
    @Query(sort: \Task.title) private var tasks: [Task]
    @Environment(\.modelContext) private var context
    
    var body: some View {
        List {
            ForEach(tasks) { task in
                HStack {
                    Text(task.title ?? &quot;&quot;)
                        .font(.title2)
                        .foregroundColor(task.isCompleted ? .green : .black)
                    
                    Spacer()
                    
                    Toggle(&quot;&quot;, isOn: Bindable(task).isCompleted)
                   
                }
            }
            .onDelete(perform: deleteTask)
        }
        .task {
            
            for task in sampleTasks {
                context.insert(task)
            }
            
        }
        .navigationTitle(&quot;Tasks&quot;)
    }
    
    private func updateTaskCompletion(_ task: Task, newValue: Bool) {
        task.isCompleted = newValue
        try? context.save()
    }
    
    private func deleteTask(at offsets: IndexSet) {
        for index in offsets {
            context.delete(tasks[index])
        }
        try? context.save()
    }
}
</code></pre>
<p>In this view, each task can be marked as completed by toggling a switch, and we handle saving this state with <strong>SwiftData</strong>.</p>
<h2>Step 3: Preview with SwiftData Context</h2>
<p>To make the preview functional, we need to set up a SwiftData context. We’ll use the <code class="" data-line="">PreviewModifier</code> protocol to create a shared context that holds some sample data.<span id="more-1765"></span></p>
<pre><code class="language-swift" data-line="">import Foundation
import SwiftUI
import SwiftData

let sampleTasks = [
    Task(title: &quot;Buy Groceries&quot;),
    Task(title: &quot;Walk the Dog&quot;, isCompleted: true),
    Task(title: &quot;Complete SwiftUI Project&quot;)
]

struct SampleTaskData: PreviewModifier {
    static func makeSharedContext() throws -&gt; ModelContainer {
        let container = try ModelContainer(for: Task.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))

        for task in sampleTasks {
            container.mainContext.insert(task)
        }
        
        return container
    }

    func body(content: Content, context: ModelContainer) -&gt; some View {
        content.modelContainer(context)
    }
}

extension PreviewTrait where T == Preview.ViewTraits {
    static var sampleTaskData: Self = .modifier(SampleTaskData())
}
</code></pre>
<p>In this example, the <code class="" data-line="">SampleTaskData</code> struct conforms to <code class="" data-line="">PreviewModifier</code>, providing a shared SwiftData context with in-memory tasks for the preview.</p>
<h2>Step 4: Add a Preview #Preview(traits:</h2>
<p>Now, let&#8217;s create a dynamic preview</p>
<pre><code class="language-swift" data-line="">#Preview(traits: .sampleTaskData) {
    TaskListView()
}</code></pre>
<h2>Step 5. Add <code class="" data-line="">@Previewable</code> to Preview</h2>
<p>Now, we&#8217;ll use the <code class="" data-line="">@Previewable</code> attribute inside the <code class="" data-line="">#Preview</code> macro to interact with the <code class="" data-line="">Task</code> completion status dynamically.</p>
<pre><code class="language-swift" data-line="">#Preview(&quot;Dynamic Task Preview&quot;) {
    @Previewable @State var isTaskCompleted = false
    let sampleTask = Task(title: &quot;Complete SwiftUI Project&quot;, isCompleted: isTaskCompleted)
    
    return HStack {
        Text(sampleTask.title ?? &quot;&quot;)
            .font(.title2)
            .foregroundColor(sampleTask.isCompleted ? .green : .black)
        
        Spacer()
        
        Toggle(&quot;&quot;, isOn: $isTaskCompleted)
    }
}</code></pre>
<p>In this preview:</p>
<ul>
<li>The <code class="" data-line="">@Previewable</code> attribute tags the <code class="" data-line="">isTaskCompleted</code> state variable.</li>
<li>This allows you to toggle the state of <code class="" data-line="">isTaskCompleted</code> directly in the Xcode preview and see real-time changes.</li>
<li>The task’s completion status will update dynamically as you interact with the toggle in the preview.</li>
</ul>
<p>This tutorial demonstrated how to display sample SwiftData in SwiftUI with PreviewModifier and @Previewable</p>
<p>The post <a href="https://appmakers.dev/how-to-display-sample-swiftdata-in-swiftui-with-previewmodifier/">How to display sample SwiftData in SwiftUI with PreviewModifier</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SwiftData Tutorial &#8211; How to Implement SwiftData in SwiftUI App</title>
		<link>https://appmakers.dev/swiftdata-tutorial/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Sat, 12 Oct 2024 03:46:05 +0000</pubDate>
				<category><![CDATA[SwiftData]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Data and Storage]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=572</guid>

					<description><![CDATA[<p>SwiftData offers a seamless way to manage and persist data with minimal effort. In this article, we&#8217;ll explore how to implement a simple SwiftData model, set up persistent storage, and manipulate data within SwiftUI views. Let&#8217;s start our SwiftData Tutorial. What is SwiftData? SwiftData is a data management framework introduced by Apple, designed to integrate&#8230;</p>
<p>The post <a href="https://appmakers.dev/swiftdata-tutorial/">SwiftData Tutorial &#8211; How to Implement SwiftData in SwiftUI App</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SwiftData offers a seamless way to manage and persist data with minimal effort. In this article, we&#8217;ll explore how to implement a simple SwiftData model, set up persistent storage, and manipulate data within SwiftUI views. Let&#8217;s start our SwiftData Tutorial.</p>
<h2>What is SwiftData?</h2>
<p>SwiftData is a data management framework introduced by Apple, designed to integrate seamlessly with Swift and SwiftUI. It provides a simple yet powerful way to manage and persist data in iOS and macOS apps without needing extensive setup. By leveraging the <code class="" data-line="">@Model</code> macro, developers can define Swift classes as persistent data models, allowing the framework to automatically handle database schemas, change tracking, and data synchronization. SwiftData also supports key features like iCloud syncing, in-memory storage for testing, and relationship management between models, making it an ideal tool for modern app development. Its deep integration with SwiftUI ensures that any changes to your data automatically trigger UI updates, simplifying the development process and enhancing the performance of data-driven apps.</p>
<h3>Step 1: Setting Up Your SwiftData Model</h3>
<p>First, let’s create a model representing something simple. In our case, we&#8217;ll model a <strong>Book</strong>. We&#8217;ll define properties such as the book&#8217;s title, author, and genre. You can add more attributes as needed.</p>
<h4>1.1 Create the Model File</h4>
<ul>
<li>Open Xcodea and. Create a new Swift file called <code class="" data-line="">Book.swift</code>.</li>
<li>Import <code class="" data-line="">SwiftData</code>.</li>
<li>Define your model class with the <code class="" data-line="">@Model</code> macro. This macro ensures that your class is recognized by SwiftData for persistence.</li>
</ul>
<pre><code class="language-swift" data-line="">import SwiftData

@Model
class Book {
    var title: String
    var author: String
    var genre: String?
    
    init(title: String, author: String, genre: String? = nil) {
        self.title = title
        self.author = author
        self.genre = genre
    }
}
</code></pre>
<p><strong>Note</strong>: Optionals are important in SwiftData because non-optional properties must always have a value. If you’re planning future migrations, use optionals (<code class="" data-line="">?</code>) for fields that could be nil.</p>
<h3>Step 2: Setting Up the Main App and Model Container</h3>
<p>Before we can persist and manipulate <code class="" data-line="">Book</code> instances, we need to configure the model container in our main app file.</p>
<h4>2.1 Set Up Model Container</h4>
<ol>
<li>In your main <code class="" data-line="">App</code> file, import <code class="" data-line="">SwiftData</code>.</li>
<li>Use the <code class="" data-line="">.modelContainer</code> modifier to declare the models that should be persisted across app launches.</li>
</ol>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

@main
struct BookApp: App {
    var body: some Scene {
        WindowGroup {
            MainView().modelContainer(for: [Book.self])
        }
    }
}
</code></pre>
<p>This setup creates a default model container that stores data persistently. If you need to use a different storage method (e.g., in-memory), you can customize it, but for this example, we&#8217;ll stick with the default.</p>
<h3>Step 3: Creating a View to Display and Modify Data</h3>
<p>Now that we have our <code class="" data-line="">Book</code> model and the model container set up, we can create a SwiftUI view to display and modify the data.</p>
<h4>3.1 Fetching Data Using <code class="" data-line="">@Query</code></h4>
<p><span id="more-572"></span></p>
<p>SwiftData simplifies fetching data with the <code class="" data-line="">@Query</code> property wrapper, allowing us to query models and automatically update the UI when data changes.</p>
<pre><code class="language-swift" data-line="">import SwiftUI
import SwiftData

struct MainView: View {
    @Query(sort: \Book.title, order: .forward) private var books: [Book]
    @Environment(\.modelContext) private var context
    
    @State private var newBookTitle = &quot;&quot;
    @State private var newBookAuthor = &quot;&quot;
    @State private var newBookGenre = &quot;&quot;
    
    var body: some View {
        NavigationStack {
            VStack {
                // List of books
                List(books) { book in
                    HStack {
                        Text(book.title)
                        Spacer()
                        Text(book.author)
                    }
                }
                
                // Form to add a new book
                VStack {
                    TextField(&quot;Title&quot;, text: $newBookTitle)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .padding()
                    TextField(&quot;Author&quot;, text: $newBookAuthor)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .padding()
                    TextField(&quot;Genre&quot;, text: $newBookGenre)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .padding()
                    
                    Button(&quot;Add Book&quot;) {
                        addNewBook()
                    }
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                }
            }
            .navigationTitle(&quot;Books&quot;)
        }
    }
    
    // Function to add a new book
    private func addNewBook() {
        let newBook = Book(title: newBookTitle, author: newBookAuthor, genre: newBookGenre.isEmpty ? nil : newBookGenre)
        context.insert(newBook)
        
        do {
            try context.save()
        } catch {
            print(&quot;Failed to save book: \(error.localizedDescription)&quot;)
        }
        
        // Reset form fields
        newBookTitle = &quot;&quot;
        newBookAuthor = &quot;&quot;
        newBookGenre = &quot;&quot;
    }
}
</code></pre>
<p>Here’s what’s happening:</p>
<ul>
<li><strong>Fetching Data</strong>: The <code class="" data-line="">@Query</code> property fetches all <code class="" data-line="">Book</code> instances, sorted by title.</li>
<li><strong>Environment Model Context</strong>: The <code class="" data-line="">@Environment(\.modelContext)</code> provides access to the current model context for saving or deleting data.</li>
<li><strong>Adding a New Book</strong>: The <code class="" data-line="">addNewBook</code> function inserts a new <code class="" data-line="">Book</code> into the context and saves the changes.</li>
</ul>
<h3>Step 4: Previewing and Working with In-Memory Storage</h3>
<p>For previews and testing, we can use an in-memory container. This prevents saving the data permanently and resets it between preview runs.</p>
<pre><code class="language-swift" data-line="">#Preview {
    MainView().modelContainer(for: [Book.self], inMemory: true)
}
</code></pre>
<p>Using in-memory storage is particularly useful when testing or running previews, as it ensures that each run starts with a clean state.</p>
<h3>Step 5: Deleting a Book</h3>
<p>You can enable deletion of items in the list by adding a swipe-to-delete action. Add this to the <code class="" data-line="">List</code> view:</p>
<pre><code class="language-swift" data-line="">List {
    ForEach(books) { book in
        HStack {
            Text(book.title)
            Spacer()
            Text(book.author)
        }
    }
    .onDelete(perform: deleteBook)
}
</code></pre>
<p>Then, define the <code class="" data-line="">deleteBook</code> function:</p>
<pre><code class="language-swift" data-line="">private func deleteBook(at offsets: IndexSet) {
    for index in offsets {
        context.delete(books[index])
    }
    
    do {
        try context.save()
    } catch {
        print(&quot;Failed to delete book: \(error.localizedDescription)&quot;)
    }
}
</code></pre>
<p>This function removes the selected <code class="" data-line="">Book</code> from the context and saves the change.</p>
<h2>Conclusion</h2>
<p>In this article, we&#8217;ve covered how to:</p>
<ul>
<li>Set up a simple model with SwiftData.</li>
<li>Create a model container to persist data.</li>
<li>Fetch and display data using <code class="" data-line="">@Query</code>.</li>
<li>Add, delete, and persist data within a SwiftUI view.</li>
</ul>
<p>SwiftData is powerful yet straightforward, making data management in SwiftUI apps easier and more efficient. You can further extend this example by adding relationships, more complex attributes, or custom storage configurations. Happy coding!</p>
<p>The post <a href="https://appmakers.dev/swiftdata-tutorial/">SwiftData Tutorial &#8211; How to Implement SwiftData in SwiftUI App</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Semantic Colors in SwiftUI: accentColor, primary, secondary, custom color</title>
		<link>https://appmakers.dev/semantic-colors-in-swiftui/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Wed, 19 Jun 2024 18:32:42 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Drawing and Animation]]></category>
		<category><![CDATA[SwiftUI Styling and Customization]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=567</guid>

					<description><![CDATA[<p>SwiftUI offers a variety of semantic colors that adapt to different contexts and system settings, enhancing the visual consistency and accessibility of your app. Semantic colors automatically adjust to the system&#8217;s color scheme and user preferences, making your app look great in both light and dark modes. This tutorial will guide you through using semantic&#8230;</p>
<p>The post <a href="https://appmakers.dev/semantic-colors-in-swiftui/">Semantic Colors in SwiftUI: accentColor, primary, secondary, custom color</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SwiftUI offers a variety of semantic colors that adapt to different contexts and system settings, enhancing the visual consistency and accessibility of your app. Semantic colors automatically adjust to the system&#8217;s color scheme and user preferences, making your app look great in both light and dark modes. This tutorial will guide you through using semantic colors in SwiftUI with unique and engaging examples.</p>
<h2>Introduction to Semantic Colors</h2>
<p>Semantic colors are predefined colors in SwiftUI that adapt to the app&#8217;s theme and accessibility settings. Some common semantic colors include <code class="" data-line="">accentColor</code>, <code class="" data-line="">primary</code>, and <code class="" data-line="">secondary</code>.</p>
<h3>Example: Using AccentColor</h3>
<p>The <code class="" data-line="">accentColor</code> is a broad theme color applied to views and controls. You can set it at the application level by specifying an accent color in your app’s asset catalog.</p>
<h4>Setting AccentColor in Asset Catalog</h4>
<ol>
<li>Open your asset catalog (Assets.xcassets).</li>
<li>Create a new color set and name it <code class="" data-line="">AccentColor</code>.</li>
<li>Choose your desired color.</li>
</ol>
<h4>Example: Using AccentColor in SwiftUI</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

@main
struct SemanticColorsApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .accentColor(.purple) // Set accent color for the entire app
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            Text(&quot;Accent Color Example&quot;)
                .foregroundStyle(Color.accentColor)
                .padding()
                .background(Color.accentColor.opacity(0.2))
                .cornerRadius(10)
            
            Button(action: {
                print(&quot;Button tapped&quot;)
            }) {
                Text(&quot;Tap Me&quot;)
                    .padding()
                    .background(Color.accentColor)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}
</code></pre>
<p>In this example, we set the accent color of the entire app to purple using the <code class="" data-line="">accentColor</code> modifier. The <code class="" data-line="">Text</code> and <code class="" data-line="">Button</code>views use the accent color to create a consistent look.</p>
<h3>Example: Using Primary and Secondary Colors</h3>
<p>The <code class="" data-line="">primary</code> and <code class="" data-line="">secondary</code> colors are used for primary and secondary content, respectively. These colors adapt to the system&#8217;s color scheme and user settings.</p>
<h4>Example: Using Primary and Secondary Colors in SwiftUI</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct PrimarySecondaryColorsView: View {
    var body: some View {
        VStack(spacing: 20) {
            Text(&quot;Primary Color Example&quot;)
                .foregroundStyle(Color.primary)
                .padding()
                .background(Color.primary.opacity(0.2))
                .cornerRadius(10)

            Text(&quot;Secondary Color Example&quot;)
                .foregroundStyle(Color.secondary)
                .padding()
                .background(Color.secondary.opacity(0.2))
                .cornerRadius(10)

            Button(action: {
                print(&quot;Primary Button tapped&quot;)
            }) {
                Text(&quot;Primary Button&quot;)
                    .padding()
                    .background(Color.primary)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }

            Button(action: {
                print(&quot;Secondary Button tapped&quot;)
            }) {
                Text(&quot;Secondary Button&quot;)
                    .padding()
                    .background(Color.secondary)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}

</code></pre>
<p>In this example, we use <code class="" data-line="">Color.primary</code> and <code class="" data-line="">Color.secondary</code> to style text and buttons. These colors adapt to the system&#8217;s light and dark modes, providing a consistent and accessible user experience.</p>
<h3>Example: Customizing System Colors</h3>
<p>In addition to predefined semantic colors, you can customize colors in SwiftUI to create a unique look for your app. Custom colors can be defined in the asset catalog or directly in code.</p>
<h4>Example: Using Custom Colors</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct CustomColorsView: View {
    var body: some View {
        VStack(spacing: 20) {
            Text(&quot;Custom Color Example&quot;)
                .foregroundStyle(Color(&quot;CustomColor&quot;))
                .padding()
                .background(Color(&quot;CustomColor&quot;).opacity(0.2))
                .cornerRadius(10)

            Button(action: {
                print(&quot;Custom Color Button tapped&quot;)
            }) {
                Text(&quot;Custom Color Button&quot;)
                    .padding()
                    .background(Color(&quot;CustomColor&quot;))
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}

</code></pre>
<p>To use custom colors:</p>
<ol>
<li>Open your asset catalog (Assets.xcassets).</li>
<li>Create a new color set and name it <code class="" data-line="">CustomColor</code>.</li>
<li>Choose your desired color.</li>
</ol>
<p>In this example, we define a custom color in the asset catalog and use it in the <code class="" data-line="">Text</code> and <code class="" data-line="">Button</code> views.</p>
<h2>Conclusion</h2>
<p>Using semantic colors in SwiftUI allows you to create visually consistent and accessible user interfaces. By leveraging <code class="" data-line="">accentColor</code>, <code class="" data-line="">primary</code>, <code class="" data-line="">secondary</code>, and custom colors, you can ensure your app looks great across different themes and user settings.</p>
<p>&nbsp;</p>
<p>The post <a href="https://appmakers.dev/semantic-colors-in-swiftui/">Semantic Colors in SwiftUI: accentColor, primary, secondary, custom color</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mastering Focus in SwiftUI: Using .focused Modifier</title>
		<link>https://appmakers.dev/swiftui-focused/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Wed, 19 Jun 2024 16:32:58 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<category><![CDATA[SwiftUI User Interaction]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=563</guid>

					<description><![CDATA[<p>SwiftUI&#8217;s .focused modifier allows you to control and observe the focus state of your views. This is particularly useful for managing user input fields and ensuring a smooth user experience. In this tutorial, we&#8217;ll explore how to use the .focused modifier with unique and interesting examples that are simple to understand for developers of all&#8230;</p>
<p>The post <a href="https://appmakers.dev/swiftui-focused/">Mastering Focus in SwiftUI: Using .focused Modifier</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SwiftUI&#8217;s <code class="" data-line="">.focused</code> modifier allows you to control and observe the focus state of your views. This is particularly useful for managing user input fields and ensuring a smooth user experience. In this tutorial, we&#8217;ll explore how to use the <code class="" data-line="">.focused</code> modifier with unique and interesting examples that are simple to understand for developers of all levels.</p>
<h2>Introduction to .focused</h2>
<p>The <code class="" data-line="">.focused</code> modifier binds the focus state of a view to a Boolean state value. When the bound value is true, the view receives focus; when false, it loses focus. This allows you to programmatically manage the focus state of your views.</p>
<h3>Basic Example</h3>
<p>Let&#8217;s start with a basic example where we manage the focus state of a <code class="" data-line="">TextField</code> in a form, including a visual indicator for when the field is focused.</p>
<pre><code class="language-swift" data-line="">import SwiftUI

struct FocusedExampleView: View {
    @State private var username: String = &quot;&quot;
    @State private var password: String = &quot;&quot;
    @FocusState private var usernameFieldIsFocused: Bool
    @FocusState private var passwordFieldIsFocused: Bool
    @State private var showPasswordHint = false

    var body: some View {
        VStack(spacing: 20) {
            TextField(&quot;Username&quot;, text: $username)
                .focused($usernameFieldIsFocused)
                .padding()
                .background(usernameFieldIsFocused ? Color.yellow.opacity(0.3) : Color.clear)
                .cornerRadius(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(usernameFieldIsFocused ? Color.blue : Color.gray, lineWidth: 2)
                )

            SecureField(&quot;Password&quot;, text: $password)
                .focused($passwordFieldIsFocused)
                .padding()
                .background(passwordFieldIsFocused ? Color.yellow.opacity(0.3) : Color.clear)
                .cornerRadius(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(passwordFieldIsFocused ? Color.blue : Color.gray, lineWidth: 2)
                )

            if showPasswordHint {
                Text(&quot;Password must be at least 8 characters long.&quot;)
                    .foregroundColor(.red)
            }

            Button(&quot;Submit&quot;) {
                validateForm()
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
        }
        .padding()
    }

    private func validateForm() {
        if username.isEmpty {
            usernameFieldIsFocused = true
        } else if password.count &lt; 8 {
            passwordFieldIsFocused = true
            showPasswordHint = true
        } else {
            showPasswordHint = false
            print(&quot;Form submitted&quot;)
        }
    }
}
</code></pre>
<h3>Explanation</h3>
<ol>
<li><strong>State Variables</strong>: We use <code class="" data-line="">@State</code> variables to store the input values for the username and password fields, and to manage the visibility of the password hint.</li>
<li><strong>FocusState</strong>: We use <code class="" data-line="">@FocusState</code> property wrappers to track the focus state of the username and password fields.</li>
<li><strong>TextField and SecureField</strong>: The <code class="" data-line="">TextField</code> for the username and the <code class="" data-line="">SecureField</code> for the password are each bound to their respective focus states using the <code class="" data-line="">.focused</code> modifier.</li>
<li><strong>Visual Indicators</strong>: We change the background color and border color of the fields to indicate when they are focused.</li>
<li><strong>Form Validation</strong>: The <code class="" data-line="">validateForm</code> function checks if the username is empty or if the password is less than 8 characters long. It sets the focus to the appropriate field and displays a hint if necessary.</li>
<li><strong>Submit Button</strong>: The &#8220;Submit&#8221; button triggers the form validation logic.</li>
</ol>
<h2>Advanced Example: Managing Multiple Focused Fields</h2>
<p>In a more complex form, you might need to manage multiple fields and their focus states. Let&#8217;s extend our example to include an email field and implement a more sophisticated focus management, with visual indicators for each field.</p>
<pre><code class="language-swift" data-line="">import SwiftUI

struct AdvancedFocusedExampleView: View {
    @State private var username: String = &quot;&quot;
    @State private var email: String = &quot;&quot;
    @State private var password: String = &quot;&quot;
    @FocusState private var usernameFieldIsFocused: Bool
    @FocusState private var emailFieldIsFocused: Bool
    @FocusState private var passwordFieldIsFocused: Bool
    @State private var showPasswordHint = false

    var body: some View {
        VStack(spacing: 20) {
            TextField(&quot;Username&quot;, text: $username)
                .focused($usernameFieldIsFocused)
                .padding()
                .background(usernameFieldIsFocused ? Color.yellow.opacity(0.3) : Color.clear)
                .cornerRadius(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(usernameFieldIsFocused ? Color.blue : Color.gray, lineWidth: 2)
                )

            TextField(&quot;Email&quot;, text: $email)
                .focused($emailFieldIsFocused)
                .padding()
                .background(emailFieldIsFocused ? Color.yellow.opacity(0.3) : Color.clear)
                .cornerRadius(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(emailFieldIsFocused ? Color.blue : Color.gray, lineWidth: 2)
                )
                .keyboardType(.emailAddress)
                .autocapitalization(.none)

            SecureField(&quot;Password&quot;, text: $password)
                .focused($passwordFieldIsFocused)
                .padding()
                .background(passwordFieldIsFocused ? Color.yellow.opacity(0.3) : Color.clear)
                .cornerRadius(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(passwordFieldIsFocused ? Color.blue : Color.gray, lineWidth: 2)
                )

            if showPasswordHint {
                Text(&quot;Password must be at least 8 characters long.&quot;)
                    .foregroundColor(.red)
            }

            Button(&quot;Submit&quot;) {
                validateForm()
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
        }
        .padding()
    }

    private func validateForm() {
        if username.isEmpty {
            usernameFieldIsFocused = true
        } else if !isValidEmail(email) {
            emailFieldIsFocused = true
        } else if password.count &lt; 8 {
            passwordFieldIsFocused = true
            showPasswordHint = true
        } else {
            showPasswordHint = false
            print(&quot;Form submitted&quot;)
        }
    }

    private func isValidEmail(_ email: String) -&gt; Bool {
        // Simple email validation
        let emailRegEx = &quot;[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}&quot;
        let emailPredicate = NSPredicate(format:&quot;SELF MATCHES %@&quot;, emailRegEx)
        return emailPredicate.evaluate(with: email)
    }
}
</code></pre>
<h3>Explanation</h3>
<ol>
<li><strong>Multiple Fields</strong>: We apply the same visual indicator logic to the username, email, and password fields.</li>
<li><strong>Form Validation</strong>: The validation logic ensures the correct field is focused based on the validation outcome.</li>
<li><strong>Email Field</strong>: The email field has its own focus state and visual indicators.</li>
</ol>
<p>By adding these visual cues, users can easily identify which field is currently active, enhancing the user experience.</p>
<h2>Conclusion</h2>
<p>Using the <code class="" data-line="">.focused</code> modifier in SwiftUI allows you to control and observe the focus state of your views, enhancing the user experience by managing input fields efficiently. By following these examples, you can implement sophisticated focus management in your SwiftUI applications.</p>
<p>&nbsp;</p>
<p>The post <a href="https://appmakers.dev/swiftui-focused/">Mastering Focus in SwiftUI: Using .focused Modifier</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Mastering Canvas, GraphicsContext, and Styles in SwiftUI</title>
		<link>https://appmakers.dev/mastering-canvas-graphicscontext-and-styles-in-swiftui/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Tue, 28 May 2024 14:36:58 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Drawing and Animation]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=559</guid>

					<description><![CDATA[<p>SwiftUI offers a rich set of tools for creating and customizing user interfaces. Among these are Canvas, GraphicsContext, Border, ForegroundStyle, and BackgroundStyle. This tutorial will guide you through the basics of these powerful features with unique and easy-to-follow examples. Introduction to Canvas Canvas is a view in SwiftUI that provides a drawing area for creating&#8230;</p>
<p>The post <a href="https://appmakers.dev/mastering-canvas-graphicscontext-and-styles-in-swiftui/">Mastering Canvas, GraphicsContext, and Styles in SwiftUI</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SwiftUI offers a rich set of tools for creating and customizing user interfaces. Among these are <code class="" data-line="">Canvas</code>, <code class="" data-line="">GraphicsContext</code>, <code class="" data-line="">Border</code>, <code class="" data-line="">ForegroundStyle</code>, and <code class="" data-line="">BackgroundStyle</code>. This tutorial will guide you through the basics of these powerful features with unique and easy-to-follow examples.</p>
<h2>Introduction to Canvas</h2>
<p><code class="" data-line="">Canvas</code> is a view in SwiftUI that provides a drawing area for creating custom graphics. It uses <code class="" data-line="">GraphicsContext</code> to draw shapes, images, and text.</p>
<h3>Example: Drawing with Canvas and GraphicsContext</h3>
<pre><code class="language-swift" data-line="">import SwiftUI

struct CanvasDrawingView: View {
    var body: some View {
        Canvas { context, size in
            context.draw(Text(&quot;Hello, SwiftUI!&quot;), at: CGPoint(x: size.width / 2, y: size.height / 2))
            
            let circle = Path(ellipseIn: CGRect(x: size.width / 4, y: size.height / 4, width: size.width / 2, height: size.height / 2))
            context.fill(circle, with: .color(.blue))
        }
        .frame(width: 300, height: 300)
        .border(Color.black, width: 2)
    }
}
</code></pre>
<p>In this example, we use <code class="" data-line="">Canvas</code> to draw text and a blue circle. The <code class="" data-line="">GraphicsContext</code> allows us to draw shapes and text at specific positions within the canvas.</p>
<h2>Using Border</h2>
<p>The <code class="" data-line="">border</code> modifier adds a border around a view. You can customize the border&#8217;s color, width, and style.</p>
<h3>Example: Applying a Border to a View</h3>
<pre><code class="language-swift" data-line="">struct BorderedView: View {
    var body: some View {
        Text(&quot;Bordered Text&quot;)
            .padding()
            .border(Color.red, width: 4)
    }
}
</code></pre>
<p>In this example, we add a red border around a text view.</p>
<h2>ForegroundStyle</h2>
<p><code class="" data-line="">ForegroundStyle</code> allows you to set the style for the foreground content of a view, such as text or shapes.</p>
<h3>Example: Using ForegroundStyle with Text</h3>
<pre><code class="language-swift" data-line="">struct ForegroundStyledView: View {
    var body: some View {
        Text(&quot;Stylized Text&quot;)
            .font(.largeTitle)
            .foregroundStyle(
                LinearGradient(
                    gradient: Gradient(colors: [.red, .orange]),
                    startPoint: .leading,
                    endPoint: .trailing
                )
            )
            .padding()
    }
}</code></pre>
<p>In this example, we use a linear gradient as the foreground style for the text, creating a smooth color transition.</p>
<h2>BackgroundStyle</h2>
<p><code class="" data-line="">BackgroundStyle</code> allows you to set the background style of a view.</p>
<pre><code class="language-swift" data-line="">struct BackgroundStyledView: View {
    var body: some View {
        Text(&quot;Stylized Background&quot;)
            .padding()
            .background(
                LinearGradient(
                    gradient: Gradient(colors: [.blue, .purple]),
                    startPoint: .top,
                    endPoint: .bottom
                )
            )
            .cornerRadius(10)
            .padding()
    }
}</code></pre>
<p>In this example:</p>
<ol>
<li>We apply a <code class="" data-line="">LinearGradient</code> as the background to a <code class="" data-line="">Text</code> view using the <code class="" data-line="">.background</code> modifier.</li>
<li>The gradient transitions from blue at the top to purple at the bottom.</li>
<li>We add a corner radius to the text view to give it rounded corners.</li>
</ol>
<h2>Conclusion</h2>
<p>SwiftUI&#8217;s <code class="" data-line="">Canvas</code>, <code class="" data-line="">GraphicsContext</code>, <code class="" data-line="">Border</code>, <code class="" data-line="">ForegroundStyle</code>, and <code class="" data-line="">BackgroundStyle</code> provide powerful tools for creating custom graphics and styling views. By understanding and using these features, you can enhance the visual appeal and functionality of your SwiftUI applications.</p>
<p>The post <a href="https://appmakers.dev/mastering-canvas-graphicscontext-and-styles-in-swiftui/">Mastering Canvas, GraphicsContext, and Styles in SwiftUI</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Clipboard &#8211; Copy and Paste in SwiftUI</title>
		<link>https://appmakers.dev/clipboard-copy-and-paste-in-swiftui/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Tue, 28 May 2024 13:43:01 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Navigation]]></category>
		<category><![CDATA[SwiftUI State Management and Data Flow]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=555</guid>

					<description><![CDATA[<p>SwiftUI provides simple and powerful APIs to interact with the system clipboard. You can easily copy text to the clipboard and retrieve text from it. Basic Usage: Copying Text to Clipboard Let&#8217;s start with a basic example where we copy a text string to the clipboard when a button is pressed. Example: Copying Text to&#8230;</p>
<p>The post <a href="https://appmakers.dev/clipboard-copy-and-paste-in-swiftui/">Clipboard &#8211; Copy and Paste in SwiftUI</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SwiftUI provides simple and powerful APIs to interact with the system clipboard. You can easily copy text to the clipboard and retrieve text from it.</p>
<h3>Basic Usage: Copying Text to Clipboard</h3>
<p>Let&#8217;s start with a basic example where we copy a text string to the clipboard when a button is pressed.</p>
<h4>Example: Copying Text to Clipboard</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct CopyTextView: View {
    @State private var textToCopy = &quot;Hello, SwiftUI!&quot;
    @State private var message = &quot;Tap the button to copy text&quot;

    var body: some View {
        VStack(spacing: 20) {
            Text(message)
                .padding()

            Text(textToCopy)
                .padding()
                .background(Color.gray.opacity(0.2))
                .cornerRadius(10)

            Button(action: {
                UIPasteboard.general.string = textToCopy
                message = &quot;Text copied to clipboard!&quot;
            }) {
                Text(&quot;Copy Text&quot;)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}</code></pre>
<p>In this example:</p>
<ol>
<li>We define a <code class="" data-line="">@State</code> variable <code class="" data-line="">textToCopy</code> that holds the text we want to copy.</li>
<li>Another <code class="" data-line="">@State</code> variable <code class="" data-line="">message</code> is used to display the status message.</li>
<li>When the button is pressed, the text is copied to the clipboard using <code class="" data-line="">UIPasteboard.general.string</code>.</li>
</ol>
<h3>Combining Copy and Paste Functionality</h3>
<p>Let&#8217;s combine the copy and paste functionality into a single view.</p>
<h4>Example: Copy and Paste Text</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct CopyPasteTextView: View {
    @State private var textToCopy = &quot;Hello, SwiftUI!&quot;
    @State private var pastedText = &quot;Tap &#039;Paste&#039; to see clipboard text&quot;

    var body: some View {
        VStack(spacing: 20) {
            Text(&quot;Text to Copy:&quot;)
            Text(textToCopy)
                .padding()
                .background(Color.gray.opacity(0.2))
                .cornerRadius(10)

            Button(action: {
                UIPasteboard.general.string = textToCopy
            }) {
                Text(&quot;Copy Text&quot;)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }

            Divider()

            Text(&quot;Pasted Text:&quot;)
            Text(pastedText)
                .padding()
                .background(Color.gray.opacity(0.2))
                .cornerRadius(10)

            Button(action: {
                if let text = UIPasteboard.general.string {
                    pastedText = text
                } else {
                    pastedText = &quot;No text found in clipboard&quot;
                }
            }) {
                Text(&quot;Paste Text&quot;)
                    .padding()
                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}
</code></pre>
<p>In this example:</p>
<ol>
<li>We define two <code class="" data-line="">@State</code> variables <code class="" data-line="">textToCopy</code> and <code class="" data-line="">pastedText</code>.</li>
<li>The &#8220;Copy Text&#8221; button copies <code class="" data-line="">textToCopy</code> to the clipboard.</li>
<li>The &#8220;Paste Text&#8221; button retrieves and displays text from the clipboard in the <code class="" data-line="">pastedText</code> variable.</li>
</ol>
<h2>Conclusion</h2>
<p>Using the clipboard in SwiftUI is straightforward and enhances the interactivity of your app. By understanding how to copy and paste text, you can create more user-friendly interfaces.</p>
<p>The post <a href="https://appmakers.dev/clipboard-copy-and-paste-in-swiftui/">Clipboard &#8211; Copy and Paste in SwiftUI</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Gradients in SwiftUI &#8211; Linear, Radial, Angular</title>
		<link>https://appmakers.dev/gradients-in-swiftui-linear-radial-angular/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Tue, 28 May 2024 12:53:45 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Drawing and Animation]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=551</guid>

					<description><![CDATA[<p>Gradients are a powerful tool in SwiftUI that allow you to create visually appealing backgrounds and effects. SwiftUI supports several types of gradients, including linear, radial, and angular gradients. This tutorial will guide you through the basics of using gradients in SwiftUI, with unique and interesting examples that are simple to understand for developers of&#8230;</p>
<p>The post <a href="https://appmakers.dev/gradients-in-swiftui-linear-radial-angular/">Gradients in SwiftUI &#8211; Linear, Radial, Angular</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Gradients are a powerful tool in SwiftUI that allow you to create visually appealing backgrounds and effects. SwiftUI supports several types of gradients, including linear, radial, and angular gradients. This tutorial will guide you through the basics of using gradients in SwiftUI, with unique and interesting examples that are simple to understand for developers of all levels.</p>
<h2>Introduction to Gradients in SwiftUI</h2>
<p>SwiftUI provides built-in support for creating gradients using the <code class="" data-line="">LinearGradient</code>, <code class="" data-line="">RadialGradient</code>, and <code class="" data-line="">AngularGradient</code> views. These gradients can be used to fill shapes, backgrounds, and more.</p>
<h3>Linear Gradient</h3>
<p>A linear gradient creates a color transition along a straight line. You can define the start and end points, as well as the colors to transition between.</p>
<h4>Example: Creating a Linear Gradient</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct LinearGradientView: View {
    var body: some View {
        Rectangle()
            .fill(
                LinearGradient(
                    gradient: Gradient(colors: [Color.red, Color.blue]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .frame(width: 200, height: 200)
    }
}
</code></pre>
<p>In this example, we create a <code class="" data-line="">Rectangle</code> filled with a linear gradient that transitions from red to blue, starting from the top leading corner to the bottom trailing corner.</p>
<h3>Radial Gradient</h3>
<p>A radial gradient creates a color transition radiating outward from a center point.</p>
<h4>Example: Creating a Radial Gradient</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct RadialGradientView: View {
    var body: some View {
        Circle()
            .fill(
                RadialGradient(
                    gradient: Gradient(colors: [Color.yellow, Color.orange]),
                    center: .center,
                    startRadius: 20,
                    endRadius: 100
                )
            )
            .frame(width: 200, height: 200)
    }
}</code></pre>
<p>In this example, we create a <code class="" data-line="">Circle</code> filled with a radial gradient that transitions from yellow at the center to orange at the edges.</p>
<h3>Angular Gradient</h3>
<p>An angular gradient creates a color transition around a circle, sweeping from one color to another.</p>
<h4>Example: Creating an Angular Gradient</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct AngularGradientView: View {
    var body: some View {
        Circle()
            .fill(
                AngularGradient(
                    gradient: Gradient(colors: [Color.purple, Color.pink, Color.purple]),
                    center: .center
                )
            )
            .frame(width: 200, height: 200)
    }
}</code></pre>
<p>In this example, we create a <code class="" data-line="">Circle</code> filled with an angular gradient that transitions from purple to pink and back to purple around the center.</p>
<h3>Using EllipticalGradient with Shapes</h3>
<p>Elliptical gradients can be applied to various shapes, not just ellipses. You can use them with rectangles, circles, and custom shapes to create unique visual effects.</p>
<h4>Example: Applying Elliptical Gradient to a Rectangle</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct EllipticalGradientRectangleView: View {
    var body: some View {
        Rectangle()
            .fill(
                EllipticalGradient(
                    gradient: Gradient(colors: [.green, .yellow]),
                    center: .center,
                    startRadiusFraction: 0.2,
                    endRadiusFraction: 0.8
                )
            )
            .frame(width: 300, height: 200)
    }
}
</code></pre>
<h3>Combining Gradients</h3>
<p>You can combine different gradients to create more complex and interesting effects.</p>
<h4>Example: Combining Linear and Radial Gradients</h4>
<pre><code class="language-swift" data-line="">struct CombinedGradientView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .fill(
                    LinearGradient(
                        gradient: Gradient(colors: [Color.blue.opacity(0.5), Color.green.opacity(0.5)]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
                .frame(width: 300, height: 300)
            
            Circle()
                .fill(
                    RadialGradient(
                        gradient: Gradient(colors: [Color.white.opacity(0.5), Color.clear]),
                        center: .center,
                        startRadius: 50,
                        endRadius: 150
                    )
                )
                .frame(width: 300, height: 300)
        }
    }
}</code></pre>
<p>In this example, we create a <code class="" data-line="">Rectangle</code> with a linear gradient background and overlay a <code class="" data-line="">Circle</code> with a radial gradient to create a more complex visual effect.</p>
<h2>Conclusion</h2>
<p>Gradients are a versatile tool in SwiftUI that can enhance the visual appeal of your app. By understanding how to use <code class="" data-line="">LinearGradient</code>, <code class="" data-line="">RadialGradient</code>, and <code class="" data-line="">AngularGradient</code>, you can create stunning effects and backgrounds.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://appmakers.dev/gradients-in-swiftui-linear-radial-angular/">Gradients in SwiftUI &#8211; Linear, Radial, Angular</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Gestures in SwiftUI: Tap, Long Tap, Drag, Rotation</title>
		<link>https://appmakers.dev/gestures-swiftui/</link>
		
		<dc:creator><![CDATA[AppMakers]]></dc:creator>
		<pubDate>Sat, 25 May 2024 09:35:28 +0000</pubDate>
				<category><![CDATA[Export Locked]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Tutorials]]></category>
		<category><![CDATA[SwiftUI User Interaction]]></category>
		<guid isPermaLink="false">https://uiexamples.com/?p=545</guid>

					<description><![CDATA[<p>Gestures play a vital role in creating interactive and intuitive user interfaces. SwiftUI offers a variety of gesture recognizers that allow you to add touch and motion-based interactions to your apps easily. This tutorial will guide you through the basics of using gestures in SwiftUI with unique and interesting examples suitable for developers of all&#8230;</p>
<p>The post <a href="https://appmakers.dev/gestures-swiftui/">Gestures in SwiftUI: Tap, Long Tap, Drag, Rotation</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Gestures play a vital role in creating interactive and intuitive user interfaces. SwiftUI offers a variety of gesture recognizers that allow you to add touch and motion-based interactions to your apps easily. This tutorial will guide you through the basics of using gestures in SwiftUI with unique and interesting examples suitable for developers of all levels.</p>
<h2>Introduction to Gestures in SwiftUI</h2>
<p>SwiftUI provides several built-in gestures such as tap, drag, long press, and rotation. You can attach these gestures to any view using the <code class="" data-line="">.gesture</code> modifier. Let&#8217;s explore each of these gestures with practical examples.</p>
<h3>Tap Gesture</h3>
<p>The tap gesture is one of the simplest and most commonly used gestures. It detects a single or multiple taps on a view.</p>
<h4>Example: Using Tap Gesture</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct TapGestureView: View {
    @State private var message = &quot;Tap on the circle&quot;

    var body: some View {
        VStack {
            Circle()
                .fill(Color.blue)
                .frame(width: 100, height: 100)
                .onTapGesture {
                    message = &quot;Circle tapped!&quot;
                }
            Text(message)
                .padding()
        }
    }
}
</code></pre>
<p>In this example, a <code class="" data-line="">Circle</code> view changes the message displayed in the <code class="" data-line="">Text</code> view when tapped.</p>
<h3>Long Press Gesture</h3>
<p>The long press gesture recognizes when a user presses and holds on a view for a specified duration.</p>
<h4>Example: Using Long Press Gesture</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct LongPressGestureView: View {
    @State private var isPressed = false

    var body: some View {
        Circle()
            .fill(isPressed ? Color.red : Color.green)
            .frame(width: 100, height: 100)
            .onLongPressGesture {
                isPressed.toggle()
            }
    }
}
</code></pre>
<p>In this example, the color of the <code class="" data-line="">Circle</code> view toggles between red and green when long pressed.</p>
<h3>Drag Gesture</h3>
<p>The drag gesture allows users to drag views across the screen.</p>
<h4>Example: Using Drag Gesture</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct DragGestureView: View {
    @State private var offset = CGSize.zero
    @State private var startLocation = CGSize.zero

    var body: some View {
        Circle()
            .fill(Color.purple)
            .frame(width: 100, height: 100)
            .offset(x: offset.width + startLocation.width, y: offset.height + startLocation.height)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        offset = CGSize(width: gesture.translation.width + startLocation.width,
                                        height: gesture.translation.height + startLocation.height)
                    }
                    .onEnded { gesture in
                        startLocation = CGSize(width: offset.width, height: offset.height)
                        offset = .zero
                    }
            )
    }
}
</code></pre>
<p>In this example, a <code class="" data-line="">Circle</code> view can be dragged around the screen.</p>
<h5>Explanation</h5>
<ol>
<li><strong>State Variables</strong>: We use <code class="" data-line="">offset</code> to track the current drag offset and <code class="" data-line="">startLocation</code> to remember the view&#8217;s position after each drag.</li>
<li><strong>onChanged</strong>: During the drag, we update <code class="" data-line="">offset</code> by adding the current gesture translation to the start location.</li>
<li><strong>onEnded</strong>: When the drag ends, we update <code class="" data-line="">startLocation</code> to the new position and reset <code class="" data-line="">offset</code> to zero for the next drag.</li>
</ol>
<h3>Rotation Gesture</h3>
<p>The rotation gesture detects rotation interactions and can be used to rotate views.</p>
<h4>Example: Using Rotation Gesture</h4>
<pre><code class="language-swift" data-line="">import SwiftUI

struct RotationGestureView: View {
    @State private var rotation: Angle = .zero
    @State private var lastRotation: Angle = .zero

    var body: some View {
        Rectangle()
            .fill(Color.orange)
            .frame(width: 200, height: 200)
            .rotationEffect(rotation + lastRotation)
            .gesture(
                RotationGesture()
                    .onChanged { angle in
                        rotation = angle
                    }
                    .onEnded { angle in
                        lastRotation += rotation
                        rotation = .zero
                    }
            )
    }
}</code></pre>
<h5>Explanation</h5>
<ol>
<li><strong>State Variables</strong>: We use <code class="" data-line="">rotation</code> to track the current rotation during the gesture and <code class="" data-line="">lastRotation</code> to remember the accumulated rotation after each gesture.</li>
<li><strong>onChanged</strong>: During the rotation, we update <code class="" data-line="">rotation</code> to the current gesture&#8217;s angle.</li>
<li><strong>onEnded</strong>: When the rotation ends, we add the current rotation to <code class="" data-line="">lastRotation</code> and reset <code class="" data-line="">rotation</code> to zero for the next gesture.</li>
</ol>
<h3>Combining Gestures</h3>
<p>SwiftUI allows you to combine multiple gestures on a single view using the <code class="" data-line="">.simultaneousGesture</code> modifier.</p>
<h4>Example: Combining Tap and Long Press Gestures</h4>
<pre><code class="language-swift" data-line="">struct CombinedGestureView: View {
    @State private var message = &quot;Tap or Long Press&quot;

    var body: some View {
        VStack {
            Circle()
                .fill(Color.blue)
                .frame(width: 100, height: 100)
                .onTapGesture {
                    message = &quot;Circle tapped!&quot;
                }
                .simultaneousGesture(
                    LongPressGesture()
                        .onEnded { _ in
                            message = &quot;Circle long pressed!&quot;
                        }
                )
            Text(message)
                .padding()
        }
    }
}</code></pre>
<h5>Explanation</h5>
<ol>
<li><strong>State Variable</strong>: We use a <code class="" data-line="">@State</code> variable <code class="" data-line="">message</code> to display the current gesture action.</li>
<li><strong>Circle View</strong>: We create a <code class="" data-line="">Circle</code> view with a blue fill, setting its frame to 100&#215;100 points.</li>
<li><strong>Tap Gesture</strong>: We use <code class="" data-line="">.onTapGesture</code> to detect tap gestures on the <code class="" data-line="">Circle</code> view. When the <code class="" data-line="">Circle</code> is tapped, it updates the <code class="" data-line="">message</code> to &#8220;Circle tapped!&#8221;.</li>
<li><strong>Long Press Gesture</strong>: We use <code class="" data-line="">.simultaneousGesture</code> to combine a <code class="" data-line="">LongPressGesture</code> with the tap gesture. When the <code class="" data-line="">Circle</code> is long-pressed, it updates the <code class="" data-line="">message</code> to &#8220;Circle long pressed!&#8221;.</li>
<li><strong>Text View</strong>: We display the <code class="" data-line="">message</code> in a <code class="" data-line="">Text</code> view below the <code class="" data-line="">Circle</code>, which updates based on the detected gesture.</li>
</ol>
<h5>How It Works</h5>
<ul>
<li><strong>Tap Gesture</strong>: When you tap on the <code class="" data-line="">Circle</code>, the <code class="" data-line="">onTapGesture</code> modifier is triggered, updating the <code class="" data-line="">message</code> to &#8220;Circle tapped!&#8221;.</li>
<li><strong>Long Press Gesture</strong>: When you long press on the <code class="" data-line="">Circle</code>, the <code class="" data-line="">onEnded</code> closure of the <code class="" data-line="">LongPressGesture</code> is triggered, updating the <code class="" data-line="">message</code> to &#8220;Circle long pressed!&#8221;.</li>
</ul>
<p>In this example, the <code class="" data-line="">Circle</code> view can detect both tap and long press gestures, updating the message accordingly.</p>
<h2>Conclusion</h2>
<p>SwiftUI gestures provide a powerful way to create interactive and responsive user interfaces. By understanding and using these gestures, you can enhance the user experience in your apps.</p>
<p>&nbsp;</p>
<p>The post <a href="https://appmakers.dev/gestures-swiftui/">Gestures in SwiftUI: Tap, Long Tap, Drag, Rotation</a> appeared first on <a href="https://appmakers.dev">AppMakers.Dev</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
