<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chandan Karmakar on Medium]]></title>
        <description><![CDATA[Stories by Chandan Karmakar on Medium]]></description>
        <link>https://medium.com/@chan.only.123?source=rss-469a6b236d96------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*vuBrFz8lf_1chm__uQ_LFQ.jpeg</url>
            <title>Stories by Chandan Karmakar on Medium</title>
            <link>https://medium.com/@chan.only.123?source=rss-469a6b236d96------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chan.only.123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bringing JUCE to Flutter: A Walk in the Park — Part 3(JUCE-UI)]]></title>
            <link>https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-3-juce-ui-bc994bdbdebf?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc994bdbdebf</guid>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[juce]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 14:53:51 GMT</pubDate>
            <atom:updated>2025-04-16T11:58:31.043Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-2-flutter-android-c3eca5bc9cb3?source=your_stories_page--------------------------------------------">Bringing JUCE to Flutter: A Walk in the Park — Part 3 (JUCE-UI)</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5H0yAYYSw-spwQexH7jlHQ.png" /></figure><p>This tutorial is a continuation of <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-1-flutter-ios-569dee72d7e8">part 1</a> and <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-2-flutter-android-c3eca5bc9cb3">part 2</a>.</p><p>To harness all the features of JUCE you need to initiate JUCE-UI properly. Basically it is similar to UI thread in iOS and Android.</p><p>Used a wrapper around JuceLibGen class.</p><pre>import &#39;dart:ffi&#39;;<br><br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter_jucer/juce_lib_gen.dart&#39;;<br><br>class JuceLibWrapper {<br>  late JuceLibGen lib;<br><br>  JuceLibWrapper() {<br>    lib = JuceLibGen(<br>        defaultTargetPlatform == TargetPlatform.iOS ? DynamicLibrary.process() : DynamicLibrary.open(&quot;libjuce_jni.so&quot;));<br>  }<br>}</pre><p>Update juce_init() <br>Insert method juce_play_test_sound to test the device sound.<br>Insert method Java_com_example_flutter_1jucer_JucerApplication_juce_1init , the name is compatible with JNI (Java Native Interface).</p><pre>#include &quot;juce_lib.h&quot;<br>#include &lt;JuceHeader.h&gt;<br><br>juce::AudioDeviceManager* deviceManager;<br><br>// For iOS<br>void juce_init() {<br>    // Main UI thread init for JUCE<br>    juce::initialiseJuce_GUI();<br><br>    // device manager init<br>    deviceManager = new juce::AudioDeviceManager();<br>    int numInputChannelsNeeded = 0;<br>    int numOutputChannelsNeeded = 2;<br>    deviceManager-&gt;initialiseWithDefaultDevices(numInputChannelsNeeded, numOutputChannelsNeeded);<br>}<br><br>// For android<br>void Java_com_example_flutter_1jucer_JucerApplication_juce_1init() {<br>    juce_init();<br>}<br><br>void juce_play_test_sound() {<br>    deviceManager-&gt;playTestSound();<br>}</pre><p>Single instance of AudioDeviceManager is used here. juce::MessageManager::getInstance() is similar to DispatchQueue.main from iOS.</p><p>Update header file with our new method.</p><pre>EXPORT_C_FUNC void juce_init();<br>EXPORT_C_FUNC void juce_play_test_sound();<br>EXPORT_C_FUNC void Java_com_example_flutter_1jucer_JucerApplication_juce_1init();</pre><p>Execute dart run ffigen to generate the dart bindings from our header file.</p><h3>Changes for iOS</h3><p>We have to call juce_init from main thread, so use ios/Runner/AppDelegate.swift . Before that import the header in ios/Runner/Runner-Bridging-Header.h</p><pre>#import &quot;GeneratedPluginRegistrant.h&quot;<br>#import &quot;../../juce_lib/Source/juce_lib.h&quot;</pre><pre>@main<br>@objc class AppDelegate: FlutterAppDelegate {<br>  override func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>  ) -&gt; Bool {<br>    juce_init() // JUCE UI thread init<br>    GeneratedPluginRegistrant.register(with: self)<br>    return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>  }<br>}</pre><p>It’s time to use juce_play_test_sound from flutter. Update main.dart file, make floating button click fires the juce_play_test_sound . playTestSound doesn’t require to be run on main thread. If a method requires main thread you would know 😉.</p><pre>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  int _counter = 0;<br>  JuceLibWrapper juce = JuceLibWrapper();<br><br>  void _incrementCounter() {<br>    juce.lib.juce_play_test_sound();<br>    setState(() {<br>      _counter++;<br>    });<br>  }<br><br>  ...<br>}</pre><p>Run the app on any iOS device and click the button, should hear a beep sound.</p><h3>Changes for Android</h3><p>Create custom Application class for android. Override onCreate and call juce methods.</p><pre>package com.example.flutter_jucer<br><br>import android.app.Application<br>import com.rmsl.juce.Java<br><br>class JucerApplication: Application() {<br><br>    // equivalent to `Java_com_example_flutter_1jucer_JucerApplication_juce_1init`<br>    private external fun juce_init()<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        Java.initialiseJUCE(this)<br>        juce_init();<br>    }<br>}</pre><p>Update AndroidManifest.xml</p><pre>&lt;application<br>        android:name=&quot;.JucerApplication&quot;</pre><p>Now run the app to an android device and tapping the same button should hear the beep sound.</p><p>Download the complete sample project from <a href="https://github.com/chanonly123/flutter_jucer_example/tree/juce-ui-init-part-3">here</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc994bdbdebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing JUCE to Flutter: A Walk in the Park — Part 2(Flutter-Android)]]></title>
            <link>https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-2-flutter-android-c3eca5bc9cb3?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3eca5bc9cb3</guid>
            <category><![CDATA[ffi]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[juce]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[ffigen]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 10:54:57 GMT</pubDate>
            <atom:updated>2025-03-28T12:24:11.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bringing JUCE to Flutter: A Walk in the Park — Part 2 (Flutter-Android)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H63YKMtkDonD9urpK_rbCQ.jpeg" /></figure><p>This is a follow up tutorial from <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-1-flutter-ios-569dee72d7e8">part 1</a></p><p><strong>Prerequisites</strong>: Macos/Windows/Linux, VSCode, flutter, Android Studio. Download JUCE framework from <a href="https://juce.com/download/">juce download page</a>. Extract it to /Users/&lt;username&gt;/JUCE/<strong> </strong>and for windows C:\JUCE\</p><p>Note: For Windows install this winget install -e — id LLVM.LLVM , required for ffigen .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*aamIK8vNdfwz_8iI.png" /></figure><p><strong>Note</strong>: This tutorial mainly focuses on configuration of the Flutter-Android project. JUCE-UI related apis are out of the scope.</p><p><strong>Step 1: Setup JUCE native library with projucer for Android<br></strong>• Use dynamic (SHARED) library only for Android<br>• Adding as dependency in Android Studio</p><p>For macos/Linux Create juce_lib/post_gen.sh with below content. This will convert the android JUCE library as SHARED (Dynamic)</p><pre>#!/bin/sh<br><br># convert to SHARED library for android<br>scriptDir=&quot;$(dirname &quot;$(realpath &quot;$0&quot;)&quot;)&quot;<br><br>awk &#39;<br>{<br>    # Trim leading and trailing spaces<br>    gsub(/^ +| +$/, &quot;&quot;, $0);<br><br>    if ($0 == &quot;STATIC&quot;) {<br>        print &quot;SHARED&quot;; <br>    } else {<br>        print $0;<br>    }<br>}<br>&#39; &quot;$scriptDir/Builds/Android/lib/CMakeLists.txt&quot; &gt; &quot;$scriptDir/Builds/Android/lib/CMakeLists_new.txt&quot;<br><br>mv &quot;$scriptDir/Builds/Android/lib/CMakeLists_new.txt&quot; &quot;$scriptDir/Builds/Android/lib/CMakeLists.txt&quot;</pre><p>For windows use juce_lib/post_gen.bat</p><pre>@echo off<br>setlocal enabledelayedexpansion<br><br>set &quot;scriptDir=%~dp0&quot;<br>set &quot;input_file=%scriptDir%Builds\Android\lib\CMakeLists.txt&quot;<br>set &quot;temp_file=%input_file%_out.txt&quot;<br><br>if not exist &quot;%input_file%&quot; (<br>    echo File not found: %input_file%<br>    exit /b 1<br>)<br><br>&gt; &quot;%temp_file%&quot; (<br>    for /f &quot;tokens=* delims=&quot; %%a in (%input_file%) do (<br>        set &quot;line=%%a&quot;<br>        set &quot;trimmed=!line: =!&quot;<br><br>        if &quot;!trimmed!&quot;==&quot;STATIC&quot; (<br>            echo SHARED<br>        ) else (<br>            echo !line!<br>        )<br>    )<br>)<br><br>move /y &quot;%temp_file%&quot; &quot;%input_file%&quot; &gt; nul<br>echo Processing complete.</pre><p>Execute open ~/JUCE/Projucer.app in terminal<br>- open juce_lib/juce_lib.jucer using Projucer<br>- and add this script to Post-Export Shell Command -&gt; /bin/sh &#39;%%1%%/post_gen.sh&#39;<br>For windows set C:\Windows\system32\cmd.exe /c %%1%%\post_gen.bat</p><p>And set Binary Name for android as juce_jni . This is required by JUCE framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9OmcnpuWs06Pvmsvc8Hrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PPKrip38aGe_JqKa9iDrLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuDVMlszJ_i4LclrGGQUMg.png" /></figure><p>Save the project by File -&gt; Save Project from menu.</p><p>Next open android project using Android Studio</p><p>Add following to android/settings.gradle.kts and android/app/build.gradle.kts</p><pre>include(&quot;:juce_jni&quot;) // same name as binary name<br>project(&quot;:juce_jni&quot;).projectDir = File(rootProject.projectDir, &quot;../juce_lib/Builds/Android/lib&quot;)</pre><pre>dependencies {<br>    implementation(project(&quot;:juce_jni&quot;))<br>}</pre><p>After <strong>Gradle Sync</strong> the project should look like this on Android Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBX4zX7NqZq1Zdzu__P7BQ.png" /></figure><p>Now update the android/lib/main.dart with below content</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br><br>Future&lt;void&gt; main() async {<br>    ...<br>    JuceLibGen lib = JuceLibGen(defaultTargetPlatform == TargetPlatform.iOS ? DynamicLibrary.process() : DynamicLibrary.open(&quot;libjuce_jni.so&quot;));<br>    ...<br>}</pre><p>We are done with the configuration, run the app on any android device, it should play the reverb version of the audio.</p><p>Download the complete sample project from <a href="https://github.com/chanonly123/flutter_jucer_example/tree/setup-juce-part-1-2">here</a>.</p><p>Continue to <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-3-juce-ui-bc994bdbdebf">initiate juce UI</a>.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3eca5bc9cb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing JUCE to Flutter: A Walk in the Park — Part 1 (Flutter-iOS)]]></title>
            <link>https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-1-flutter-ios-569dee72d7e8?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/569dee72d7e8</guid>
            <category><![CDATA[ffigen]]></category>
            <category><![CDATA[juce]]></category>
            <category><![CDATA[ffi]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 07:35:26 GMT</pubDate>
            <atom:updated>2025-03-31T11:53:51.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bringing JUCE to Flutter: A Walk in the Park — Part 1 (Flutter-iOS)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H63YKMtkDonD9urpK_rbCQ.jpeg" /></figure><p><strong>JUCE is a powerful C++ framework for audio applications, widely used for plugins and cross-platform development. Projucer, JUCE’s project management tool, simplifies setup, code generation, and multi-platform builds.</strong></p><p>I have been using JUCE for a year. I love to share that with Dart and C++, a single codebase can power high-performance audio/video applications across iOS, Android, macOS, and Windows.</p><p>We’re going to use JUCE native library and include that to our iOS project as dependency. Then apply simple reverb effect to an audio file and save output to a file.</p><p><strong>Note</strong>: This tutorial mainly focuses on configuration of the Flutter-iOS project. JUCE-UI related apis are out of the scope.</p><p><strong>Prerequisites</strong>: Macos, VSCode, flutter, for iOS Xcode, Cocoapods. Download JUCE framework from <a href="https://juce.com/download/">juce download page</a>. Extract it to /Users/&lt;username&gt;/JUCE/</p><p>Note: For Windows the projucer setup is similar, then continue with <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-2-flutter-android-c3eca5bc9cb3">Android tutorial</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*wEFnRpW2oTDhgwzU9WV_zA.png" /></figure><p><strong>Step 1: Setup Flutter project</strong><br>• Putting a audio file in assets<br>• Extracting audio file from bundle<br>• Playing audio file</p><p><strong>Step 2: Setup JUCE native library with projucer<br></strong>• Use static library<br>• Create simple test C function<br>• Use ffigen to generate flutter bindings from C header<br>• Adding as dependency<br>• Call the function from flutter (ffi/ffigen)</p><p><strong>Step 3: Write simple reverb function<br></strong>• Read the file into buffer<br>• Add reverb effect to the buffer<br>• Save the buffer to a file<br>• Consume the method from flutter</p><h3><strong>Step 1: Setup Flutter project</strong></h3><p>Open terminal and execute flutter create flutter_jucer<br>Open flutter project with VSCode and make sure it runs on iOS/Android <br>device.<br>Add below dependencies<br>flutter pub add path_provider<br>flutter pub add just_audio<br>flutter pub add ffi<br>flutter pub add -d ffigen</p><p>Create file lib/asset_helper.dart , needed for getting the audio file from bundle and ready to be pass into JUCE processing and playing.</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39; as path;<br><br>class AssetHelper {<br>  static String? _tempGetApplicationDocumentsDirectoryPath;<br><br>  static Future&lt;String&gt; getApplicationDocumentsDirectoryPath() async =&gt;<br>      _tempGetApplicationDocumentsDirectoryPath ??= (await path.getApplicationDocumentsDirectory()).path;<br><br>  static Future&lt;String&gt; extractAsset(String assetPath) async {<br>    final documentsDirpath = await getApplicationDocumentsDirectoryPath();<br>    String path = &quot;$documentsDirpath/$assetPath&quot;;<br>    ByteData data = await rootBundle.load(assetPath);<br>    final buffer = data.buffer;<br>    final file = File(path);<br>    await file.create(recursive: true);<br>    await file.writeAsBytes(buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));<br>    return path;<br>  }<br><br>}</pre><p>Copy audio file to asset/media, assets/media/audio.wav <br>Update pubspec.yaml</p><pre>assets:<br>    - assets/media/</pre><p>Update main.dart and run it on android/iOS device. It should play the audio file.</p><pre>Future&lt;void&gt; main() async {<br>  runApp(const MyApp());<br><br>  final player = AudioPlayer();<br>  var input = await AssetHelper.extractAsset(&#39;assets/media/audio.wav&#39;);<br>  await player.setFilePath(input);<br>  await player.play();<br>}</pre><h3><strong>Step 2: Setup JUCE native library with projucer</strong></h3><p>Execute open ~/JUCE/Projucer.app in terminal.<br>File -&gt; New Project -&gt; Static Library <br>Set some project name, Select juce modules to include, select Exporters iOS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5UamkbMgYkMj7od4RaNSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxkQggnux5enmU0QA5PRtw.png" /></figure><p>Then clickCreate Project button, then select our flutter project directory.</p><p>Now let’s add some simple native methods to test our library.</p><p>Create .cpp and .h files in File Explorer in Projucer. Right click on Source and select Create new cpp and header file with below contents.</p><pre>// juce_lib/Source/juce_lib.h<br><br>#pragma once<br><br>#ifdef __cplusplus<br>#define EXPORT_C_FUNC extern &quot;C&quot; __attribute__((visibility(&quot;default&quot;))) __attribute__((used))<br>#else<br>#define EXPORT_C_FUNC extern<br>#endif<br><br>EXPORT_C_FUNC int juce_add(int a, int b);</pre><pre>// juce_lib/Source/juce_lib.cpp<br><br>#include &quot;juce_lib.h&quot;<br><br>int juce_add(int a, int b) {<br>    return a + b;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*UScnL3k2TuKFSxpNOHFEpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*wAOFQ4bzLVOjEo5KqnZZ3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I15YW1s5Wv92q8uTqPA5VA.png" /></figure><p>Don’t forget to save the <strong>Projucer</strong> file by File -&gt; Save Project . It will regenerate the library projects to juce_lib/Builds/iOS and juce_lib/Builds/Android.</p><p>Now let’s generate flutter binding from the C header file. Append below lines to pubspec.yaml</p><pre>ffigen:<br>  name: &#39;JuceLibGen&#39;<br>  description: &#39;Generate c header to dart bindings&#39;<br>  output: &#39;lib/juce_lib_gen.dart&#39;<br>  headers:<br>    entry-points:<br>      - &#39;juce_lib/Source/juce_lib.h&#39;<br>  type-map:<br>    &#39;native-types&#39;:<br>      &#39;char&#39;:<br>        &#39;lib&#39;: &#39;pkg_ffi&#39;<br>        &#39;c-type&#39;: &#39;Utf8&#39;<br>        &#39;dart-type&#39;: &#39;Utf8&#39;</pre><p>Now execute flutter pub get and dart run ffigen in terminal. It should generate lib/juce_lib_gen.dart with juce_add function.</p><p>Note: For Windows install this winget install -e — id LLVM.LLVM , required for ffigen .</p><p>Update lib/main.dart with following content</p><pre>import &#39;dart:ffi&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_jucer/juce_lib_gen.dart&#39;;<br><br>Future&lt;void&gt; main() async {<br>  runApp(const MyApp());<br><br>  JuceLibGen lib = JuceLibGen(DynamicLibrary.process());<br>  int result = lib.juce_add(2, 3); // native function call through ffi<br>  print(&quot;result: $result&quot;);<br>}</pre><p>Next we need to add juce_lib as iOS project dependency. <br>- Open iOS workspaceios/Runner.xcworkspace using Xcode. <br>- Drag juce_lib/Builds/iOS/juce_lib.xcodeproj to Runner <br>- Add target dependency and Link it as well.<br>- Add -all_load flag to Other linker flags in Build settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*nKmXvbM70r1gXULykSfJWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyW78GHAU_KEezpwK4j1Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*9SwhQWPj3B8rrsEQUGIGjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITIDKPzT9-4N5emrOPwMBg.png" /></figure><p>Run the app from Xcode or VSCode, you should see the result in the debug console.</p><p>We have linked against our native library successfully, next step is to use the reverb effect on our audio file. Use wav format for this tutorial.</p><p>Go ahead and append below content to the header file and cpp file.</p><pre>// juce_lib/Source/juce_lib.h<br><br>EXPORT_C_FUNC int juce_apply_reverb_effect(const char* inputFile, const char* outputFile);</pre><pre>// juce_lib/Source/juce_lib.cpp<br><br>#include &lt;JuceHeader.h&gt;<br><br>int juce_apply_reverb_effect(const char* inputFile, const char* outputFile) {<br>    DBG(&quot;juce_processAudioFile start&quot;);<br><br>    juce::AudioFormatManager formatManager;<br>    formatManager.registerBasicFormats();<br>    std::unique_ptr&lt;juce::AudioFormatReader&gt; reader(formatManager.createReaderFor(juce::String(inputFile)));<br><br>    if (!reader) {<br>        DBG(&quot;Failed to read input file!&quot;);<br>        return 1;<br>    }<br><br>    // create audio buffer in memory<br>    juce::AudioBuffer&lt;float&gt; buffer(reader-&gt;numChannels, (int)reader-&gt;lengthInSamples);<br><br>    // read the audio file into buffer<br>    reader-&gt;read(&amp;buffer, 0, (int)reader-&gt;lengthInSamples, 0, true, true);<br><br>    // Apply Reverb effect<br>    juce::Reverb reverb;<br>    juce::Reverb::Parameters params;<br>    params.roomSize = 0.5f;<br>    params.wetLevel = 0.2f;<br>    params.dryLevel = 0.2f;<br>    reverb.setParameters(params);<br>    for (int i=0; i&lt;reader-&gt;numChannels; i++) {<br>        reverb.processStereo(buffer.getWritePointer(i), buffer.getWritePointer(i), buffer.getNumSamples());<br>    }<br><br>    // Write output file<br>    juce::File outFile(outputFile);<br>    outFile.deleteFile();<br>    juce::WavAudioFormat wavFormat;<br>    std::unique_ptr&lt;juce::FileOutputStream&gt; outputStream(juce::File(outputFile).createOutputStream());<br>    if (!outputStream) {<br>        DBG(&quot;Failed to create output file!&quot;);<br>        return 2;<br>    }<br><br>    std::unique_ptr&lt;juce::AudioFormatWriter&gt; writer(wavFormat.createWriterFor(<br>                                                                              outputStream.get(), reader-&gt;sampleRate, buffer.getNumChannels(), 16, {}, 0));<br>    if (!writer) {<br>        DBG(&quot;Failed to create writer!&quot;);<br>        return 3;<br>    }<br>    <br>    outputStream.release();<br>    writer-&gt;writeFromAudioSampleBuffer(buffer, 0, buffer.getNumSamples());<br><br>    DBG(&quot;juce_processAudioFile complete!&quot;);<br>    return 0;<br>}</pre><p>Also link below libraries, required by JUCE framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrpoWQRvL_WprfIAlc9g4A.png" /></figure><p>Go back to terminal and execute dart run ffigen again to generate the dart bindings for new reverb function.</p><p>Update lib/main.dart and run on any iOS device. You should be able to hear the reverb audio.</p><pre>import &#39;dart:ffi&#39;;<br><br>import &#39;package:ffi/ffi.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_jucer/asset_helper.dart&#39;;<br>import &#39;package:flutter_jucer/juce_lib_gen.dart&#39;;<br>import &#39;package:just_audio/just_audio.dart&#39;;<br><br>Future&lt;void&gt; main() async {<br>  runApp(const MyApp());<br><br>  JuceLibGen lib = JuceLibGen(DynamicLibrary.process());<br>  int result = lib.juce_add(2, 3);<br>  print(&quot;result: $result&quot;);<br><br>  var input = await AssetHelper.extractAsset(&#39;assets/media/audio.wav&#39;);<br>  var appPath = await AssetHelper.getApplicationDocumentsDirectoryPath();<br>  var output = &quot;$appPath/output.wav&quot;;<br>  var reverbOutput = lib.juce_apply_reverb_effect(<br>      input.toNativeUtf8(),<br>      output.toNativeUtf8()<br>  );<br>  print(&quot;processAudio: $reverbOutput&quot;);<br><br>  final player = AudioPlayer();<br>  await player.setFilePath(output);<br>  await player.play();<br>}</pre><p>Download the complete sample project from <a href="https://github.com/chanonly123/flutter_jucer_example/tree/setup-juce-part-1-2">here</a>.</p><p>In the next part we will continue the same with <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-2-flutter-android-c3eca5bc9cb3">Android tutorial</a>.</p><p>Then we will have <a href="https://medium.com/@chan.only.123/bringing-juce-to-flutter-a-walk-in-the-park-part-3-juce-ui-bc994bdbdebf">JUCE UI initialization</a>.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=569dee72d7e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Text — things you can do]]></title>
            <link>https://medium.com/@chan.only.123/swiftui-text-things-you-can-do-557a2a10e260?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/557a2a10e260</guid>
            <category><![CDATA[attributed-string]]></category>
            <category><![CDATA[links]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[text]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 12:03:15 GMT</pubDate>
            <atom:updated>2024-04-09T12:14:47.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGRdyssDPcGPTe2tFp0JFQ.png" /></figure><h3>SwiftUI Text — things you can do</h3><p>Explore the versatile capabilities of SwiftUI’s Text view, from basic formatting to advanced styling, localization, and dynamic content rendering.</p><h3>Dynamic Size</h3><pre>Text(&quot;Hello World&quot;)<br>    .font(.title)<br><br>Text(&quot;Hello World&quot;)<br>    .font(.title)<br>    .lineLimit(1)<br>    .minimumScaleFactor(0.5)<br>    .frame(width: 70)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*SYCwSPxRaB1tTG9g1Y8wcA.png" /></figure><h3>Concatenation</h3><pre>Text(&quot;Hello&quot;).font(.title) + Text(&quot; World&quot;).font(.subheadline)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*6MO532ZRnx8UvoRDPFtHgQ.png" /></figure><h3><strong>Localization</strong></h3><pre>// use of this overloaded init<br>Text.init(<br>    _ key: LocalizedStringKey,<br>    tableName: String? = nil,<br>    bundle: Bundle? = nil,<br>    comment: StaticString? = nil<br>)<br><br>Text(&quot;Visit my [website](https://www.apple.com)&quot;)<br>            <br>let key: LocalizedStringKey = &quot;Visit my [website](https://www.apple.com)&quot;<br>Text(key)<br><br>Text(&quot;This is normal text&quot;)<br>Text(&quot;This is **bold** text, this is *italic* text, this is ***bold, italic*** text.&quot;)<br>Text(&quot;~~strikethrough~~&quot;)<br>Text(&quot;`monospaced`&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcLoJAUY2W1nKYRPeowPtQ.png" /></figure><h3>Link color</h3><pre>Text(&quot;Visit my [website](https://www.apple.com)&quot;)<br>    .tint(.red)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*90Oa8_-tlEQTRkEN-9dHpA.png" /></figure><h3>Link click detection</h3><pre>Text(&quot;Visit my [website](https://www.apple.com)&quot;)<br>    .environment(\.openURL, OpenURLAction { url in<br>        print(&quot;clicked \(url)&quot;)<br>        return .handled<br>    })</pre><h3>Inline Text replacement</h3><pre>Text(&quot;This is \(Text(&quot;red&quot;).foregroundColor(.red).bold()) text&quot;)<br><br>// all the methods those returns Text are supported<br>// custom types need to conform LocalizedStringKey.StringInterpolation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*reXHaMczcaafq9G_cTZuNA.png" /></figure><h3>Auto update Dates</h3><pre>let date = Date(timeIntervalSinceNow: 60*60)<br>let now = Date()<br><br>var body: some View {<br>    VStack {<br>        Text(&quot;Date \(now, style: .date)&quot;)<br>        Text(&quot;Time \(now, style: .time)&quot;)<br>        <br>        Text(&quot;Time left \(date, style: .relative)&quot;)<br>        Text(&quot;Timer \(date, style: .timer)&quot;)<br>        <br>        Text(&quot;Time passed \(now, style: .offset)&quot;)<br>    }<br>    .monospacedDigit()<br>    <br>    .frame(width: 300)<br>    .padding(40)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7fIs2KyDLuZL1VdCMLQo2A.gif" /></figure><p>Comment if you have something interesting about SwiftUI Texts.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557a2a10e260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super simple Dependency Injection in Swift]]></title>
            <link>https://medium.com/@chan.only.123/super-simple-dependency-injection-in-swift-db5c3a556f8e?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/db5c3a556f8e</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 11:33:39 GMT</pubDate>
            <atom:updated>2024-03-06T12:16:02.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nWvSZdhq54wv-G2IGJeDEA.png" /></figure><p>It sounds fancy, but what exactly does it mean? Don’t worry; it’s not as complicated as it sounds. In this beginner’s guide, we’ll break down the concept of dependency injection in a simple and understandable way.</p><p>Imagine you’re baking a cake. You need ingredients like flour, eggs, and sugar. Now, let’s say you have a friend who loves baking and always has these ingredients ready. Instead of going to the store every time you need something, you can simply ask your friend for the ingredients you need. This is somewhat similar to how dependency injection works in software development.</p><p>Similarly let assume we have a simple dependency graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hNBVs6ZdhmynSoOgUbEVQ.png" /></figure><p><strong>ViewModel</strong> depends on <strong>ApiRepo, </strong>which depends on <strong>DBRepo.</strong></p><p>Now the idea is <strong>ViewModel</strong> doesn’t create its dependency <strong>ApiRepo </strong>directly, it asks <strong>injector</strong> for it.</p><p>So this is our target:</p><pre>class ViewModel {<br>    lazy var repo: ApiRepo = injector.inject()<br>    <br>    func doLogin(email: String, pass: String) {<br>        repo.login(email: email, pass: pass)<br>    }<br>}<br><br>let viewm = ViewModel()<br>viewm.doLogin(email: &quot;apple@mail.com&quot;, pass: &quot;swift&quot;)</pre><p>Swift has all the features that can help us write our own DI logic easily. In this tutorial we will use <strong>lazy</strong> properties instead of <strong>constructors</strong>.</p><p>ApiRepo implementation:</p><pre>protocol ApiRepo {<br>    func login(email: String, pass: String)<br>}<br><br>class ApiRepoService: ApiRepo {<br>    lazy var db: DBRepo = injector.inject()<br>    <br>    func login(email: String, pass: String) {<br>        print(&quot;login api call&quot;)<br>        db.getUser(email: email, pass: pass)<br>    }<br>}</pre><p>DBRepo implementation:</p><pre>protocol DBRepo {<br>    func getUser(email: String, pass: String)<br>}<br><br>class DBRepoService: DBRepo {<br>    func getUser(email: String, pass: String) {<br>        print(&quot;getUser db call&quot;)<br>    }<br>}</pre><p>Now comes Injector</p><pre>protocol Injector {<br>    func inject() -&gt; ApiRepo<br>    func inject() -&gt; DBRepo<br>}<br><br>class MainInjector: Injector {<br>    func inject() -&gt; ApiRepo {<br>        ApiRepoService()<br>    }<br>    func inject() -&gt; DBRepo {<br>        DBRepoService()<br>    }<br>}<br><br>let injector: Injector = MainInjector()<br>// let injector: Injector = isPreview ? MockInjector() : MainInjector()</pre><p>Here we are returning actual implementation of DBRepo and ApiRepo .</p><p>injector used as a shared instance.</p><p>And thats it, super simple version of DI, you can use it in your projects.</p><p>Hope you liked it.</p><p>Like and Comment 👨🏻‍💻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db5c3a556f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turbocharged SwiftUI Previews: Exploring Modularization with SPM]]></title>
            <link>https://medium.com/@chan.only.123/quick-swiftui-previews-exploring-leaf-ui-modules-with-spm-fda1cc0bcf0f?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/fda1cc0bcf0f</guid>
            <category><![CDATA[slow]]></category>
            <category><![CDATA[preview]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[faster]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 13:43:07 GMT</pubDate>
            <atom:updated>2024-02-01T08:48:03.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0VHpQVFiLBZ5cPac6OYAIQ@2x.png" /></figure><p>Hey Devs,</p><p>Ever notice SwiftUI previews slowing down 🐌 as your project balloons? It’s a common struggle! Modularize your Code. Less dependency faster preview updates. Break down your UI into separate modules. Each module handles a specific bunch of views.</p><p><strong>Experience with Swift Generics is recommended.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3PJYs9ytHaetxnVFGA3Sg.png" /></figure><p><strong>Data, Protocols: </strong>It contains only raw data structures and protocols. It doesn&#39;t depend on anything.</p><p><strong>Gallery UI/Profile UI: </strong>It contains only swiftUI views and uses the Data, Protocol from the dependency.</p><p><strong>Core</strong>: It contains ViewModels, UseCases and all the business logic.</p><p>Note: For simplicity UI module is not the pure leaf module. Else we end up writing lots of protocols and conformances. That would be overkill.</p><p>Lets dive into code!</p><p>Create a simple iOS app project. Name it <strong>GalleryApp</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnTNN_7u_fqLtyoM8ykF_w.png" /></figure><p>We will be using <strong>Swift Package Manager </strong>for managing dependencies.</p><p>Now create a package, from <strong>Xcode -&gt; File -&gt; New -&gt; Package, </strong>select <strong>empty</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QijhabLgB6IRaTJw3_WLOQ.png" /></figure><p>Select root <strong>GalleryApp </strong>directory click <strong>Create.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Qbx1F8HG0LjoqIEMmX64A.png" /></figure><p>Create multiple folder inside <strong>Modules </strong>which will contains all the modules and files. <strong>GalleryCore, GalleryUI, GalleryData. </strong>Folder structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NhZy3RfkqiMPWyLlXjVHGg.png" /></figure><p>Update Package.swift file defining dependencies. Double click it to open in Xcode.</p><pre>// swift-tools-version: 5.9<br>// The swift-tools-version declares the minimum version of Swift required to build this package.<br><br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;Modules&quot;,<br>    platforms: [<br>        .iOS(.v14)<br>    ],<br>    products: [<br>        .library(<br>            name: &quot;GalleryModules&quot;,<br>            targets: [&quot;GalleryCore&quot;,<br>                      &quot;GalleryUI&quot;,<br>                      &quot;GalleryData&quot;])<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;GalleryCore&quot;,<br>            dependencies: [&quot;GalleryData&quot;],<br>            path: &quot;GalleryCore&quot;<br>        ),<br>        <br>        .target(<br>            name: &quot;GalleryUI&quot;,<br>            dependencies: [&quot;GalleryData&quot;],<br>            path: &quot;GalleryUI&quot;<br>        ),<br>    <br>        .target(<br>            name: &quot;GalleryData&quot;,<br>            path: &quot;GalleryData&quot;<br>        )<br>    ]<br>)</pre><p>Create file GalleryData/GalleryBean.swift. Lets add some dummy data for testing.</p><pre>import Foundation<br><br>public struct GalleryBean: Codable, Hashable {<br>    public let url: String<br>    <br>    init(url: String) {<br>        self.url = url<br>    }<br>}<br><br>public extension GalleryBean {<br>    static let dummyList: [GalleryBean] = [<br>        .init(url: &quot;https://picsum.photos/id/17/200/133&quot;),<br>        .init(url: &quot;https://picsum.photos/id/15/200/133&quot;),<br>        .init(url: &quot;https://picsum.photos/id/11/200/133&quot;),<br>        .init(url: &quot;https://picsum.photos/id/14/200/133&quot;)<br>    ]<br>}</pre><p>Create file GalleryData/GalleryImageViewModel.swift<strong> . </strong>This is view model protocol declaration. It just contains a GalleryBean and the view can download the image and save it in the image variable.</p><pre>import Foundation<br>import UIKit<br><br>@MainActor<br>public protocol GalleryImageViewModel: ObservableObject {<br>    var item: GalleryBean { get }<br>    var image: UIImage? { get }<br>}</pre><p>Next let create some UI with previews.</p><p>Create file GalleryUI/GalleryImageView.swift</p><pre>import SwiftUI<br>import GalleryData<br><br>public struct GalleryImageView&lt;Model: GalleryImageViewModel&gt;: View {<br>    @StateObject var model: Model<br>    <br>    public var body: some View {<br>        if let image = model.image {<br>            Image(uiImage: image)<br>        } else {<br>            ProgressView()<br>                .colorInvert()<br>        }<br>    }<br>}<br><br>class GalleryImageViewModelPreview: GalleryImageViewModel {<br>    let item: GalleryBean<br>    @Published var image: UIImage?<br>    <br>    public init(item: GalleryBean) {<br>        self.item = item<br>        image = createDummyImage(size: CGSize(width: 100, height: 100))<br>    }<br>    <br>    func createDummyImage(size: CGSize) -&gt; UIImage {<br>        let color = [UIColor.red, .yellow, .green, .blue, .orange].randomElement()!<br>        let renderer = UIGraphicsImageRenderer(size: size)<br>        let image = renderer.image { context in<br>            color.setFill()<br>            context.fill(CGRect(origin: .zero, size: size))<br>        }<br>        return image<br>    }<br>}<br><br>#Preview {<br>    GalleryImageView(model: GalleryImageViewModelPreview(item: GalleryBean.dummyList.first!))<br>}</pre><p>Now comes to the tricky part where the we use this protocol. struct GalleryImageView&lt;Model: GalleryImageViewModel&gt;: View we have to pass class information to use it. GalleryImageViewModelPreview confronts to the required ViewModel protocol.</p><p>If there is still error, just add an empty swift file in GalleryCore/File.swift and you can see the preview for GalleryImageView .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tC--cc8vejqVNx7sPJbzng.png" /></figure><p>Now we create the gallery view where multiple GalleryImageView will be there.</p><p>Lets create the GalleryData/GalleryViewModel.swift . For protocol to pass class info, we have to use associatedtype . Here constrained by GalleryImageViewModel.</p><pre>import Foundation<br><br>@MainActor<br>public protocol GalleryViewModel: ObservableObject {<br>    associatedtype SubModel: GalleryImageViewModel<br>    var items: [SubModel] { get set }<br>}</pre><p>Create file GalleryUI/GalleryView.swift</p><pre>import SwiftUI<br>import GalleryData<br><br>public struct GalleryView&lt;Model: GalleryViewModel&gt;: View {<br>    @StateObject var model: Model<br><br>    public init(model: Model) {<br>        self._model = StateObject(wrappedValue: model)<br>    }<br>    <br>    public var body: some View {<br>        List {<br>            ForEach(model.items, id: \.self) { item in<br>                GalleryImageView(model: item)<br>            }<br>        }<br>        .listStyle(.plain)<br>    }<br>}<br><br>class GalleryViewModelPreview: GalleryViewModel {<br>    @Published var items: [GalleryImageViewModelPreview]<br>    <br>    init() {<br>        self.items = GalleryBean.dummyList.map { GalleryImageViewModelPreview(item: $0) }<br>    }<br>    <br>}<br><br>#Preview {<br>    GalleryView(model: GalleryViewModelPreview())<br>}</pre><p>GalleryViewModelPreview creates object ofGalleryImageViewModelPreview array.</p><p>To use in ForEach , add Hashable requirements to GalleryImageViewModel</p><pre>@MainActor<br>public protocol GalleryImageViewModel: ObservableObject, Hashable {<br>    var item: GalleryBean { get }<br>    var image: UIImage? { get }<br>}</pre><p>and in GalleryImageView.swift</p><pre>extension GalleryImageViewModelPreview {<br>    func hash(into hasher: inout Hasher) {}<br>    <br>    static func == (lhs: GalleryImageViewModelPreview, rhs: GalleryImageViewModelPreview) -&gt; Bool {<br>        lhs === rhs<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2_Z2QhNEddp_3y2wFOK_g.png" /></figure><p>Now you can add actual view model implementations for GalleryViewModel , GalleryImageViewModel in <strong>GalleryCore </strong>module</p><pre>import GalleryData<br>import UIKit<br><br>public class GalleryImageViewModelImpl: GalleryImageViewModel { ...<br><br>public class GalleryViewModelImpl: GalleryViewModel { ...</pre><p>Note that, GalleryCore is not dependent on the GalleryUI . Since all the protocol declaration are in the GalleryData module.</p><p>Finally open GalleryApp.xcodeproj and add local dependency to our Modules .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sX_l0sgacYaUgUxmqKeWxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h18rfw0_cl1MAHEEf_fQ1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcrxnteeRGLhZEUXO-zGrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srcaRH3E6CXz07gErJK46g.png" /></figure><p>You should be able to use the views and models from the module like this. You may need to make few items public as required.</p><pre>import SwiftUI<br>import GalleryData<br>import GalleryCore<br>import GalleryUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        GalleryView(model: GalleryViewModelImpl())<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>If you’re still with me, let’s take it up a notch — time to add some tests to the mix! 😆</p><p>Close the app project and double click Package.swift . Append a testTarget to Package.swift . Also exclude Test.swift from GalleryCore module.</p><pre>.target(<br>            name: &quot;GalleryCore&quot;,<br>            dependencies: [&quot;GalleryData&quot;],<br>            path: &quot;GalleryCore&quot;,<br>            exclude: [&quot;tests/Test.swift&quot;]<br>        ),<br>.testTarget(<br>            name: &quot;GalleryCoreTests&quot;,<br>            dependencies: [&quot;GalleryData&quot;, &quot;GalleryCore&quot;],<br>            path: &quot;GalleryCore/tests&quot;<br>        ),</pre><p>Add file GalleryCore/tests/Test.swift</p><pre>import XCTest<br>import GalleryData<br>import GalleryCore<br><br>final class Test: XCTestCase {<br><br>    @MainActor<br>    func testExample1() throws {<br>        let galleryViewModel = GalleryViewModelImpl()<br>        XCTAssert(galleryViewModel.items.isEmpty == false)<br>    }<br>    <br>    @MainActor<br>    func testExample2() throws {<br>        let imageModel = GalleryImageViewModelImpl(item: GalleryBean.dummyList[0])<br>        XCTAssert(imageModel.image != nil)<br>    }<br><br>}</pre><p>Project should look like this. Run tests from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8bAImsVR2xEXrZYvxeslw.png" /></figure><p>The sample source code is available <a href="https://github.com/chanonly123/gallery-app-swiftui-leaf"><strong>here</strong></a>.</p><p>That’s a wrap for now! Thanks for joining the ride 🙌🏼. Your time and attention mean the world. Would love to hear your thoughts — drop a comment or hit me up. Appreciate your feedback. Until next time, happy coding! 🚀💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda1cc0bcf0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a simple 2D air hockey game in iOS using UIKit Dynamics part 1]]></title>
            <link>https://medium.com/@chan.only.123/create-a-simple-2d-air-hockey-game-in-ios-using-uikit-dynamics-part-1-202ee3da60f7?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/202ee3da60f7</guid>
            <category><![CDATA[hockey]]></category>
            <category><![CDATA[gamer]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[begineers]]></category>
            <category><![CDATA[uikit-dynamics]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 06:48:54 GMT</pubDate>
            <atom:updated>2023-09-04T18:58:40.950Z</atom:updated>
            <content:encoded><![CDATA[<p>We will harness the power of the UIKit Dynamics library for our project. This library simplifies the process by imbuing UIViews with characteristics akin to physical objects in the real world. These “objects” possess attributes such as weight, velocity, acceleration, gravitational interaction, and collision behavior, allowing us to create realistic and engaging animations and interactions in our app.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have the following:</p><ul><li>Xcode installed on your Mac.</li><li>Basic knowledge of Swift programming.</li><li>Creativity and enthusiasm!</li></ul><p>You should follow the steps and run each time to check its working properly before moving to the next step.</p><h3><strong>Step 1: Review the requirements</strong></h3><ol><li><strong>Puck</strong> and <strong>Strikers</strong> which share similar properties. They are circular with the only different being their size, we can work with that. We can create a class can represent these objects.</li><li>The <strong>Board</strong> can be represented by another class, which can hold <strong>Puck</strong> and <strong>Strikers</strong>. It also has boundaries on all four sides to contain the objects.</li><li><strong>Strikers</strong> cannot cross into the opponent’s space, while the <strong>Puck</strong> can freely move around the <strong>Board</strong>.</li><li>If the <strong>Puck</strong> collides with the top or bottom sides, it should count as a score for the opposite player.</li></ol><p>Let’s jump into code now.</p><h3>Step 2: Set Up the project</h3><p>Fire up Xcode and create a new project. Select <strong>UIKit</strong> instead of <strong>SwiftUI</strong> and choose only the <strong>Portrait</strong> mode of <strong>orientation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJt2FDm1bk5g-99_dJpSAQ.png" /></figure><h3>Step 3: Create views and placements</h3><p>Create two custom <strong>UIViews</strong>: <strong>CircularView</strong> to represent the <strong>puck</strong> and <strong>Strikers</strong>, and <strong>BoardView</strong> to represent the Board. Create 2 strikers, 1 puck, and a couple of items needed in the ViewController.swift file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3-x1M_h6fDRrkqgLQRMnA.png" /></figure><pre>class CircularView: UIView {<br>    <br>    // to make the view circular<br>    override func layoutSubviews() {<br>        super.layoutSubviews()<br>        layer.cornerRadius = bounds.height / 2<br>    }<br>}</pre><pre>class BoardView: UIView { }</pre><pre>class ViewController: UIViewController {<br>    <br>    let color1 = UIColor.red<br>    let color2 = UIColor.blue<br>    <br>    var lblMiddle: UILabel!<br>    var lbl1: UILabel!<br>    var lbl2: UILabel!<br>    <br>    let strikerSize = 60<br>    let ballSize = 40<br>    <br>    var striker1: CircularView!<br>    var striker2: CircularView!<br>    var puck: CircularView!<br>    var boardView: BoardView!<br>    <br>    var player1SideView: UIView!<br>    var player2SideView: UIView!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        player1SideView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height / 2))<br>        <br>        player2SideView = UIView(frame: CGRect(x: 0.0, y: view.frame.height / 2, width: view.frame.width, height: view.frame.height / 2))<br>        <br>        boardView = BoardView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))<br>        <br>        striker1 = CircularView(frame: CGRect(x: 0, y: 0, width: strikerSize, height: strikerSize))<br>        striker1.backgroundColor = color1<br>        striker1.center = player1SideView.center<br>        <br>        striker2 = CircularView(frame: CGRect(x: 0, y: 0, width: strikerSize, height: strikerSize))<br>        striker2.backgroundColor = color2<br>        striker2.center = player2SideView.center<br>        <br>        puck = CircularView(frame: CGRect(x: 0, y: 0, width: ballSize, height: ballSize))<br>        puck.backgroundColor = .black<br>        puck.center = CGPoint(x: boardView.frame.size.width / 2, y: boardView.frame.size.height / 2)<br>        <br>        boardView.addSubview(striker1)<br>        boardView.addSubview(striker2)<br>        boardView.addSubview(player1SideView)<br>        boardView.addSubview(player2SideView)<br>        boardView.addSubview(puck)<br>        view.addSubview(boardView)<br>    }<br>}</pre><p>Utilize the frame property to position the views in their respective locations. player1SideView and player2SideView are required for touch events for both players and do not require any dynamics. Currently, the <strong>BoardView</strong> class does not have any methods, but we will need it in the future. Run the project, and it will resemble the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*mmfYFjc0Q7u3YM2xyEjrhQ.png" /></figure><h3>Step 4: Control the strikers with touch</h3><p>Add the following code to the ViewController. This code will enable the strikers to move when we drag them with our finger. Call addGestureRecognizers() at the end of the viewDidLoad method.</p><pre>override func viewDidLoad() {<br>    ...<br>    addGestureRecognizers()<br>}<br><br>var animator: UIDynamicAnimator!<br>var snap1: UISnapBehavior!<br>var snap2: UISnapBehavior!<br><br>func addGestureRecognizers() {<br>    animator = UIDynamicAnimator(referenceView: boardView)<br>    <br>    player1SideView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan1(_:))))<br>    player1SideView.isUserInteractionEnabled = true<br>    <br>    player2SideView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan2(_:))))<br>    player2SideView.isUserInteractionEnabled = true<br>}<br><br>@objc func handlePan1(_ gesture: UIGestureRecognizer) {<br>    if snap1 != nil {<br>        animator.removeBehavior(snap1)<br>    }<br>    let locTo = gesture.location(in: boardView)<br>    snap1 = UISnapBehavior(item: striker1, snapTo: locTo)<br>    animator.addBehavior(snap1)<br>}<br><br>@objc func handlePan2(_ gesture: UIGestureRecognizer) {<br>    if snap2 != nil {<br>        animator.removeBehavior(snap2)<br>    }<br>    let locTo = gesture.location(in: boardView)<br>    snap2 = UISnapBehavior(item: striker2, snapTo: locTo)<br>    animator.addBehavior(snap2)<br>}</pre><p><strong>UIDynamicAnimator</strong> provides physics-related capabilities and animations, with the boardView serving as the reference coordinate system.</p><p>Each time the finger moves, a new location is sent to the gesture handler, and on each movement, we create a new <strong>UISnapBehaviour</strong> to snap the striker to the new touch location. It&#39;s important to remove the previous snap object, as failing to do so may cause confusion regarding where to snap.</p><p>Run the project, and you&#39;ll be able to move the strikers by dragging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*oEHaesSTRV3cU3izXMYnlg.gif" /></figure><h3>Step 5: Bring them to life</h3><p>Enable collisions between them by adding UICollisionBehavior to our previously created UIDynamicAnimator object. UICollisionBehavior allows items to collide with each other. Call addCollisionBehavior() at the end of the viewDidLoad method.</p><pre>override func viewDidLoad() {<br>    ...<br>    addCollisionBehaviour()<br>}<br><br>var collision: UICollisionBehavior!<br>    <br>func addCollisionBehaviour() {<br>    collision = UICollisionBehavior(items: [striker1, striker2, puck])<br>    animator.addBehavior(collision)<br>}</pre><p>That’s it! When you run the project, you’ll be able to hit the puck with the striker now. However, there’s one issue: the collision bounds of the CircularView are currently the square frames of the striker and puck, resulting in a visible gap when colliding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*cw8HCpTgO0fWd6ES4TX1pQ.gif" /></figure><p>To resolve this issue, override collisionBoundsType for CircularView and set it to UIDynamicItemCollisionBoundsType.ellipse. This adjustment will utilize the view&#39;s height and width to establish circular collision bounds, addressing the gap problem during collisions.</p><pre>class CircularView: UIView {<br>    ...<br><br>    public override var collisionBoundsType: UIDynamicItemCollisionBoundsType {<br>        return .ellipse<br>    }<br>}</pre><p>Now, all the items are in contact with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*Vuz5X84thhncKa6Seh9DXw.gif" /></figure><h3>Step 6: Add boundaries</h3><p>First, incorporate these helpful extensions that will simplify our tasks.</p><pre>extension CGRect {<br>    var end: CGPoint {<br>        return CGPoint(x: origin.x + size.width, y: origin.y + size.height)<br>    }<br>    var topRight: CGPoint {<br>        return CGPoint(x: origin.x + size.width, y: origin.y)<br>    }<br>    var botLeft: CGPoint {<br>        return CGPoint(x: origin.x, y: origin.y + size.height)<br>    }<br>}<br><br>extension CGPoint {<br>    func offsetBy(x x_: CGFloat, y y_: CGFloat) -&gt; CGPoint {<br>        return CGPoint(x: x + x_, y: y + y_)<br>    }<br>}<br><br>extension NSCopying {<br>    var string: String {<br>        return self as! String<br>    }<br>}<br><br>extension String {<br>    var nsCopying: NSCopying {<br>        return self as NSCopying<br>    }<br>}</pre><p>Add the following code to establish boundaries and prevent objects from going outside the BoardView.</p><pre>var collision: UICollisionBehavior!<br>var collision1: UICollisionBehavior!<br>var collision2: UICollisionBehavior!<br><br>func addCollisionBehaviour() {<br>    collision = UICollisionBehavior(items: [striker1, striker2, puck])<br>    animator.addBehavior(collision)<br>    <br>    // add boundaries for puck<br>    collision.addBoundary(withIdentifier: &quot;boundary_side_top&quot;.nsCopying, from: boardView.bounds.origin, to: boardView.bounds.topRight)<br>    collision.addBoundary(withIdentifier: &quot;boundary_side_left&quot;.nsCopying, from: boardView.bounds.origin, to: boardView.bounds.botLeft)<br>    collision.addBoundary(withIdentifier: &quot;boundary_side_right&quot;.nsCopying, from: boardView.bounds.topRight, to: boardView.bounds.end)<br>    collision.addBoundary(withIdentifier: &quot;boundary_side_bot&quot;.nsCopying, from: boardView.bounds.botLeft, to: boardView.bounds.end)<br>    <br>    collision1 = UICollisionBehavior(items: [striker1])<br>    collision1.addBoundary(withIdentifier: &quot;boundary_striker1&quot;.nsCopying, for: UIBezierPath(rect: player1SideView.frame))<br>    <br>    collision2 = UICollisionBehavior(items: [striker2])<br>    collision2.addBoundary(withIdentifier: &quot;boundary_striker2&quot;.nsCopying, for: UIBezierPath(rect: player2SideView.frame))<br>    <br>    animator.addBehavior(collision)<br>    animator.addBehavior(collision2)<br>    animator.addBehavior(collision1)<br>}</pre><p>Now, as the puck can move through the board, we’ve added four edges to the collision as boundaries. We use different identifiers (boundary_side_top and boundary_side_bot) to detect a score when the puck collides with these boundaries. Additionally, to prevent strikers from entering the other player&#39;s space, we&#39;ve added the playerSideView.frame as a boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*vKioFzRc-Kb6EIzPIj4Aow.gif" /></figure><h3>Step 7: Game logic</h3><p>Now that all dynamics-related properties are functioning correctly, it’s time to conclude the game by implementing the score logic and resetting the objects to their initial positions. Before doing that, let’s display the score count on each player’s side and a central message for the final result, such as ‘Player 1/2 Wins’.</p><pre>var lblMiddle: UILabel!<br>var lbl1: UILabel!<br>var lbl2: UILabel!<br><br> override func viewDidLoad() {<br>    ...<br>    lbl1 = UILabel(frame: CGRect.zero)<br>    lbl1.font = UIFont.boldSystemFont(ofSize: 120)<br>    lbl1.textColor = color1.withAlphaComponent(0.2)<br>    lbl1.textAlignment = .right<br>    lbl1.frame = player1SideView.frame.insetBy(dx: 20, dy: 0)<br>    lbl1.text = &quot;0&quot;<br>    <br>    lbl2 = UILabel(frame: CGRect.zero)<br>    lbl2.font = UIFont.boldSystemFont(ofSize: 120)<br>    lbl2.textColor = color2.withAlphaComponent(0.2)<br>    lbl2.textAlignment = .left<br>    lbl2.frame = player2SideView.frame.insetBy(dx: 20, dy: 0)<br>    lbl2.text = &quot;0&quot;<br>    <br>    lblMiddle = UILabel(frame: boardView.bounds)<br>    lblMiddle.textAlignment = .center<br>    lblMiddle.text = &quot;&quot;<br>    lblMiddle.font = UIFont.boldSystemFont(ofSize: 60)<br>    lblMiddle.textColor = .black.withAlphaComponent(0.5)<br><br>    boardView.addSubview(lbl1)<br>    boardView.addSubview(lbl2)<br>    boardView.addSubview(lblMiddle)<br>    ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*o1vSjnUWyAdEKaqtcVeYMA.gif" /></figure><p>Let’s set up detection for when the Puck hits the top and bottom edges.</p><pre><br><br>func addCollisionBehaviour() {<br>    ...<br>    collision.collisionDelegate = self<br>}<br><br>extension ViewController: UICollisionBehaviorDelegate {<br>    func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {<br>        if item === puck {<br>            if identifier?.string == &quot;side_top&quot; {<br>                print(&quot;score player 1&quot;)<br>                score(player: 1)<br>            } else if identifier?.string == &quot;side_bot&quot; {<br>                print(&quot;score player 2&quot;)<br>                score(player: 1)<br>            }<br>        }<br>    }<br>}</pre><p>Now we can increase score count and display the results.</p><pre>func score(player: Int) {<br>    // disable everything<br>    boardView.isUserInteractionEnabled = false<br>    <br>    // remove all behaviours<br>    animator.removeAllBehaviors()<br>    <br>    // hide puck after score<br>    puck.alpha = 0<br>    <br>    var lblAnim: UILabel!<br>    if player == 1 {<br>        lbl2.text = &quot;\(Int(lbl2.text!)! + 1)&quot;<br>        lblAnim = lbl2<br>    } else {<br>        lbl1.text = &quot;\(Int(lbl1.text!)! + 1)&quot;<br>        lblAnim = lbl1<br>    }<br>    lblMiddle.text = &quot;Win player \(player)&quot;<br>    <br>    // add little scale animation to the labels<br>    UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveEaseInOut], animations: {<br>        lblAnim.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)<br>        self.lblMiddle.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)<br>    }, completion: { _ in<br>        UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveEaseInOut], animations: {<br>            lblAnim.transform = CGAffineTransform.identity<br>            self.lblMiddle.transform = .identity<br>        }, completion: nil)<br>    })<br>    <br>    // afte 2 seconds restart the game<br>    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {<br>        self.restartGame()<br>    }<br>}</pre><p>The score() method takes an argument (1/2) to determine which player scores in the game. To prevent user interaction with the board during this time, we disable it. Then, we set the labels accordingly and apply a small animation effect to them. After a 2-second delay, the restartGame() method resets the middle label and removes any remaining behaviors. Finally, we use animation to return the Puck and Strikers to their respective locations.</p><pre>func restartGame() {<br>        // reset middle lable<br>    lblMiddle.text = &quot;&quot;<br>    <br>    // again remove behaviours if any left<br>    animator.removeAllBehaviors()<br>    <br>    // puck and striker reposition animated<br>    UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveEaseInOut], animations: {<br>        self.striker1.center = self.player1SideView.center<br>        self.striker2.center = self.player2SideView.center<br>        self.puck.center = self.boardView.center<br>        self.puck.alpha = 1<br>    }) { _ in<br>        // add all behaviours again after animation<br>        self.boardView.isUserInteractionEnabled = true<br>        self.addCollisionBehaviour()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ux7vIsKhWJe6JmEoek8Sjw.gif" /></figure><p>Congratulations! You’ve learned how to create a basic two-player air hockey game using Swift and UIKit Dynamics. You can now explore further enhancements, such as adding sound effects or improving the game’s visuals in the part 2 which is coming soon.</p><p>Here is the complete project link.</p><p><a href="https://github.com/chanonly123/air_hockey_ios">GitHub - chanonly123/air_hockey_ios: Example of 2D air hockey 2 player game with UIView physics, swift.</a></p><p>Thank you for following along with this tutorial. Feel free to leave comments or questions, and don’t forget to share your modified versions of the game or your own game development projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=202ee3da60f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrapping up boilerplate code — part 1: Interface builder]]></title>
            <link>https://medium.com/@chan.only.123/wrapping-up-boilerplate-code-part-1-interface-builder-f6180fd06feb?source=rss-469a6b236d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6180fd06feb</guid>
            <category><![CDATA[wrapping]]></category>
            <category><![CDATA[removing]]></category>
            <category><![CDATA[interface-builder]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[boilerplate-code]]></category>
            <dc:creator><![CDATA[Chandan Karmakar]]></dc:creator>
            <pubDate>Fri, 01 May 2020 11:25:22 GMT</pubDate>
            <atom:updated>2020-06-01T07:38:59.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wrapping up boilerplate code — part 1: Interface builder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvV32mS-GlvjKBRVecYs6w.jpeg" /></figure><p>Working as full time iOS app developer, I would like to share few tips on ‘How to wrap boilerplate code for interface builder in swift’.</p><p>Most of us have time constraints and have to deliver projects ASAP. This led us to copy-paste code and develop redundant codebase. Copy-pasting seems easy solution first, but as project grows, it becomes less readable and hard to maintain. So let’s take a quick look here.</p><h4>Using Storyboards</h4><p>We’re familiar with instantiating view controllers from storyboard, i.e</p><pre><strong>let </strong>storyboard<strong> = </strong>UIStoryboard(name: “Main”, bundle: <strong>nil</strong>)<strong><br>let</strong> viewController = storyboard.instantiateViewController(withIdentifier: “ProfileViewController”) <strong>as</strong>! ProfileViewController</pre><p>Now let’s simplify the above code:-</p><ul><li>Our view controller will tell which storyboard they are defined,</li><li>and also its storyboardId.</li></ul><p>So goal is to write ProfileViewController.instantiate().</p><p>We need extension: UIViewControlle for this. And we’ll use class func, similar to static func. But class func comes with override facility, and that is going to help us to achieve our goal. @objc is required for overriding the variable.</p><pre><strong>extension</strong> UIViewController { <br>    @objc <strong>class var</strong> fromStoryboard: UIStoryboard? { <br>        <strong>return</strong> <strong>nil</strong> <br>    } <br>    @objc <strong>class var</strong> storyboardId: String { <br>        <strong>return</strong> String(describing: <strong>self</strong>) <br>    }<br>}</pre><p>Now we just need to provide the fromStoryboard to find it where. storyboardId is optional, it’s default implementation assumes that we have class name as storyboardId. String(describing: self) by default gives the exact class name in String. self in class function is class type itself.</p><p>Finally let’s implement instantiate().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6afafe6ed1b2333cc2c798299f7b3706/href">https://medium.com/media/6afafe6ed1b2333cc2c798299f7b3706/href</a></iframe><p>Self is Generic class type and it denotes from which class is used to call the method. Here comes the time to utilise instantiate() method. We should create UIStoryboard objects somewhere else to easily access them.</p><pre><strong>class</strong> MyStorybaords {<br>    <strong>static</strong> <strong>var</strong> main = UIStoryboard(name: “Main”, bundle: <strong>nil</strong>)<br>    <strong>static</strong> <strong>var</strong> profile = UIStoryboard(name: “Profile”, bundle: <strong>nil</strong>)<br>    ....<br>}</pre><pre><strong>class </strong>ProfileViewController: UIViewController {<br>    <strong>override</strong> <strong>class</strong> <strong>var</strong> fromStoryboard: UIStoryboard? { <br>        <strong>return</strong> MyStorybaords.profile <br>    }<br>}</pre><p>Voila, Thats all! Now we can instantiate view controllers by writing simply</p><p>let viewController = ProfileViewController.instantiate()</p><h4>Using xib to load UIViews</h4><p>With a little modification, the same can be used for instantiating UIView from xib files. Again method initViewFromNib() assumes same filename is same to class name. Leaving you to add flexibility.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c547e2c0f9e4fc395125696d8611aed4/href">https://medium.com/media/c547e2c0f9e4fc395125696d8611aed4/href</a></iframe><p>Another example of UITableView reusable cell dequeue and register</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a4c519d221e30abb74e771c54186d3/href">https://medium.com/media/29a4c519d221e30abb74e771c54186d3/href</a></iframe><p>Here we don’t need static or class function, since we would have UITableView object. Parameter type takes the cell type and we can get the cell by its class name. Same can be applied to UICollectionView.</p><p><strong>let</strong> cell = tableView.dequeueReusableCell(type: MyCustomCell.<strong>self</strong>)</p><h4>Using IBDesignable UIView from Xib</h4><p>Let’s see another instance when we use <strong>@</strong>IBDesignable<strong> </strong>to instantiate views from xib files, we can use inheritance to wrap those codes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab8f5aa0ae4bbbd903628d579077d0b/href">https://medium.com/media/eab8f5aa0ae4bbbd903628d579077d0b/href</a></iframe><p>Now we can inherit from UIViewXib and design <em>view</em> in xib file with no extra code for loading views from xib.</p><pre><strong>class</strong> DayView: UIViewXib {   <br>    // other things...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeLHjC1vQ2dtaNhJXxr_BQ.png" /></figure><p>Use this DayView to another view in interface builder. UIStackView is used to add 7 DayView objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zPBc059df54itOfoERu5w.png" /></figure><p>More optimised version of UIViewXib is here.(Assuming <strong>Autolayout</strong> is used to create xib files.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf7e54eddbe75f946862685490b19fd/href">https://medium.com/media/6bf7e54eddbe75f946862685490b19fd/href</a></iframe><p>Thats all for today flocks.</p><p>Keep improving yourself until you reach your goal. Even a small change can make huge difference.</p><p>Thanks for reading, feedback are always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6180fd06feb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>