<?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 Manisha Roy on Medium]]></title>
        <description><![CDATA[Stories by Manisha Roy on Medium]]></description>
        <link>https://medium.com/@roy11manisha?source=rss-5ba78b73ee00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*OZvL86jf1dUEY6N3eLH7rw.jpeg</url>
            <title>Stories by Manisha Roy on Medium</title>
            <link>https://medium.com/@roy11manisha?source=rss-5ba78b73ee00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:16:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roy11manisha/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[Why my speech only user struggling to perform actions?]]></title>
            <link>https://medium.com/@roy11manisha/why-my-speech-only-user-struggling-to-perform-actions-4a6ea19338f6?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a6ea19338f6</guid>
            <category><![CDATA[digital-accessibility]]></category>
            <category><![CDATA[mobile-accessibility]]></category>
            <category><![CDATA[wcag-accessibility]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[wcag-compliance]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 15:20:55 GMT</pubDate>
            <atom:updated>2026-02-25T15:20:55.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hzwbRAb_oS8luI5i" /><figcaption>Photo by <a href="https://unsplash.com/@gamergeni?utm_source=medium&amp;utm_medium=referral">Muhammad Asim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Label in Name</h3><p><strong>Rule Id: </strong><a href="https://www.w3.org/WAI/WCAG22/Understanding/label-in-name">2.5.3 Label in Name</a></p><p>When users issue voice commands based on what they see (the visible label), but the system recognizes only the accessible name, it can lead to command failure.</p><p>The accessible name is the text that assistive technologies (like screen readers) announce to users. It should ideally match or closely relate to the visible label text. If the accessible name (which may be defined in the code) does not match the visible label (what users see), the user may not recognize the button’s function based on what they hear.</p><p>Ensure that the accessible name exactly matches the visible label text for buttons and interactive elements.</p><p><strong>Read</strong>: <a href="https://www.w3.org/WAI/WCAG22/Techniques/failures/F96.html">Failure due to the accessible name not containing the visible label text</a></p><h4>Conclusion</h4><p>In conclusion, speech input users often struggle to perform actions when there is a mismatch between the visible label and the accessible name of interactive elements. Under <strong>WCAG Rule 2.5.3 — Label in Name</strong>, the accessible name must contain (and ideally match) the visible label text. When it does not, voice commands based on what users see on the screen may fail because the system recognizes only the accessible name defined in the code.</p><p>To prevent these issues, developers must ensure that the accessible name accurately reflects the visible label text for all buttons and controls. Aligning these labels improves usability, enhances accessibility for speech and assistive technology users, and ensures compliance with accessibility standards. Consistency between what users see and what the system recognizes is essential for reliable and inclusive interaction.</p><p>We encourage you to read <a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><em>“Accessibility Bites for the Digital World”</em> </a>and share your thoughts and insights. Your engagement is crucial as we work together to build a more inclusive digital world. Stay tuned for more Accessibility Bites, where we will continue to explore essential topics that empower us to make a difference in our community and beyond.</p><p><strong>Keep posted on </strong><a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><strong><em>Accessibility Bites for the Digital World</em></strong></a><strong><em> for more interesting topics.</em></strong></p><p><strong>Co-author: </strong><a href="https://medium.com/@atultiwari123452"><strong>Atul Tiwari</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a6ea19338f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wondering where is your heading?]]></title>
            <link>https://medium.com/@roy11manisha/wondering-where-is-your-heading-dda3072bff97?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/dda3072bff97</guid>
            <category><![CDATA[digital-accessibility]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[wcag-accessibility]]></category>
            <category><![CDATA[mobile-accessibility]]></category>
            <category><![CDATA[wcag-compliance]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 15:08:21 GMT</pubDate>
            <atom:updated>2026-02-25T15:08:21.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MdDbV3AJdb8IA8qM" /><figcaption>Photo by <a href="https://unsplash.com/@mindspacestudio?utm_source=medium&amp;utm_medium=referral">Mindspace Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Info and Relationships</h3><p><strong>Rule ID</strong>: <a href="https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships">1.3.1 Info and Relationships</a></p><p>Are you wondering where is your heading or struggling to differentiate the plain text and the heading?</p><p>The reason can be that you missed to use &lt;h1&gt; to &lt;h6&gt; tags or do proper role assignment to the elements like &lt;div&gt;s. <br>Not providing headings can make the content less accessible, harder to navigate, and impact its usability for users with disabilities. It can also affect the overall user experience and hinder the discoverability of the content on search engines.</p><p><strong>Read</strong>: <a href="https://www.w3.org/WAI/WCAG22/Techniques/aria/ARIA12.html">Using role=heading to identify headings</a></p><h4><strong>Conclusion</strong></h4><p>Clear and properly structured headings are essential for creating accessible, user-friendly, and well-organized content. By correctly using &lt;h1&gt; to &lt;h6&gt; tags or assigning appropriate roles such as role=&quot;heading&quot;, you ensure that information is logically structured and easily understood by both users and assistive technologies. Proper heading implementation not only improves navigation for people with disabilities but also enhances overall usability and search engine discoverability. Taking the time to apply semantic structure correctly helps create inclusive digital experiences that benefit everyone.</p><p>We encourage you to read <a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><em>“Accessibility Bites for the Digital World”</em> </a>and share your thoughts and insights. Your engagement is crucial as we work together to build a more inclusive digital world. Stay tuned for more Accessibility Bites, where we will continue to explore essential topics that empower us to make a difference in our community and beyond.</p><p><strong>Keep posted on </strong><a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><strong><em>Accessibility Bites for the Digital World</em></strong></a><strong><em> for more interesting topics.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dda3072bff97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can we skip non-text content?]]></title>
            <link>https://medium.com/@roy11manisha/can-we-skip-non-text-content-ee5461cf9813?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee5461cf9813</guid>
            <category><![CDATA[image-accessibility]]></category>
            <category><![CDATA[mobile-accessibility]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[w3c-standards]]></category>
            <category><![CDATA[wcag]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 08:41:33 GMT</pubDate>
            <atom:updated>2026-01-27T08:59:32.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVJtukqDmign8fL7" /><figcaption>Photo by <a href="https://unsplash.com/@typerium?utm_source=medium&amp;utm_medium=referral">Typerium App</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Non-text Content</h3><p><strong>Rule ID: </strong><a href="https://www.w3.org/WAI/WCAG22/Understanding/non-text-content">1.1.1 Non-text Content</a></p><p>According to WCAG, skipping image content announcement is not acceptable. WCAG requires that non-text content, such as images, have text alternatives that can be presented to users who cannot perceive the images. This ensures that individuals with visual impairments or who use assistive technologies can still understand the content and functionality provided by the images. Providing alternative text descriptions, or “alt text,” for images is a common way to meet this requirement.</p><p>But there can be cases where we want to skip giving alternative text for eg. image with some decorative information or only brush effects. For this WCAG have provided a provision to pass alt text as null or empty.</p><p><strong>Read</strong> <strong>more</strong>: <a href="https://www.w3.org/WAI/WCAG22/Techniques/html/H67.html">Using null alt text and no title attribute on img elements for images that assistive technology should ignore</a></p><h4><strong>Conclusion:</strong></h4><p>In this article, we explore the concept of providing alternative text (alt text) for images, captions for videos, and transcripts for audio content. By doing so, we emphasize that non-text content should not be an obstacle for users who rely on assistive technologies. This aligns perfectly with the overarching mission of our Accessibility Bites series: to break down complex accessibility topics into manageable pieces that foster a culture of inclusion and awareness.</p><p>We encourage you to read <a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><em>“Accessibility Bites for the Digital World”</em> </a>and share your thoughts and insights. Your engagement is crucial as we work together to build a more inclusive digital world. Stay tuned for more Accessibility Bites, where we will continue to explore essential topics that empower us to make a difference in our community and beyond.</p><p><strong>Keep posted on </strong><a href="https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2"><strong><em>Accessibility Bites for the Digital World</em></strong></a><strong><em> for more interesting topics.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee5461cf9813" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessibility Bites for Digital world]]></title>
            <link>https://medium.com/@roy11manisha/accessibility-bites-for-digital-world-6b1e5c16dbb2?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1e5c16dbb2</guid>
            <category><![CDATA[mobile-accessibility]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[accessibility-tips]]></category>
            <category><![CDATA[digital-accessibility]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 08:35:01 GMT</pubDate>
            <atom:updated>2026-02-25T15:21:40.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXOoR_YA2LW2Jyb7" /><figcaption>Photo by <a href="https://unsplash.com/@hi_muhammad_salim?utm_source=medium&amp;utm_medium=referral">Muhammad Salim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Digital accessibility is the practice of designing and developing websites, tools, and technologies to ensure that individuals with disabilities can interact with them effectively. This is crucial because over 1.3 billion people — approximately 16% of the global population — live with significant disabilities. Creating inclusive digital experiences is not only a moral obligation but also often a legal requirement in many jurisdictions.</p><h3>Accessibility Bites</h3><p>Accessibility Bites are short, focused resources or tips that help individuals and organizations improve accessibility in various contexts, such as websites, applications, and physical spaces. Here’s how they can be helpful:</p><p><strong>1. Concise Learning</strong></p><ul><li>Bite-sized Information: Accessibility Bites provide quick, digestible pieces of information that are easy to understand and implement.</li><li>Targeted Focus: Each bite usually covers a specific topic, allowing learners to concentrate on one area at a time.</li></ul><p><strong>2. Practical Tips</strong></p><ul><li>Actionable Advice: They often include practical strategies or checklists that can be immediately applied to enhance accessibility.</li><li>Real-world Examples: Many Bites provide examples of both good and bad practices, helping to illustrate key concepts.</li></ul><p><strong>3. Awareness Raising</strong></p><ul><li>Understanding Importance: By highlighting the significance of accessibility, these resources raise awareness about the needs of people with disabilities.</li><li>Promoting Inclusion: They encourage a more inclusive mindset among designers, developers, and organizations.</li></ul><p><strong>4. Resource for Training</strong></p><ul><li>Educational Tool: Accessibility Bites can serve as a resource in training sessions or workshops, making it easier to educate teams about accessibility.</li><li>Continuous Learning: They can be used for ongoing education, keeping teams updated on best practices and new guidelines.</li></ul><p><strong>5. Encouraging Best Practices</strong></p><ul><li>Standardizing Practices: By following these bites, organizations can work towards standardizing accessibility practices across their projects.</li><li>Compliance with Guidelines: They often reference established guidelines (like WCAG), helping organizations stay compliant with legal standards.</li></ul><h3>Key Principles of Digital Accessibility (POUR)</h3><p>The Web Content Accessibility Guidelines (WCAG) provide a framework for achieving digital accessibility, built upon four foundational principles known as POUR:</p><ol><li><strong>Perceivable</strong></li></ol><ul><li>Information and user interface components must be presented in ways that users can perceive. This means that all content should be accessible to all users, regardless of their sensory abilities.</li><li>For example, images should include descriptive alt text that conveys the same information to users who rely on screen readers. Videos should have captions or transcripts to ensure that individuals who are deaf or hard of hearing can access the content. Additionally, color contrast should be sufficient to ensure that text is readable for users with visual impairments.</li></ul><p><strong>2. Operable</strong></p><ul><li>Users must be able to navigate and operate the interface effectively. This principle emphasizes the need for all functionalities to be accessible, regardless of the input method.</li><li>For instance, all interactive elements, such as buttons and links, should be keyboard-accessible, allowing users who cannot use a mouse to navigate through the site. Additionally, users should have the ability to pause, stop, or adjust content that moves or auto-updates, ensuring they have control over their experience.</li></ul><p><strong>3. Understandable</strong></p><ul><li>The content and user interface must be clear and intuitive. This principle focuses on ensuring that users can easily comprehend the information presented to them.</li><li>This can be achieved by using simple language, providing clear instructions, and ensuring that the layout is logical and consistent. For example, forms should have clearly labeled fields and error messages should be descriptive, guiding users on how to correct any mistakes.</li></ul><p><strong>4. Robust</strong></p><ul><li>Content must be compatible with a wide range of technologies, including assistive technologies such as screen readers, speech recognition software, and alternative input devices.</li><li>This principle emphasizes the importance of using standard coding practices and technologies that allow for future compatibility. For example, using semantic HTML helps ensure that assistive technologies can accurately interpret and present content to users.</li></ul><p>By adhering to these four principles — Perceivable, Operable, Understandable, and Robust — organizations can create digital environments that are inclusive and accessible to all users, regardless of their abilities. This not only enhances user experience but also promotes equality and compliance with legal standards, ultimately benefiting society as a whole.</p><h3>Conclusion</h3><p>Accessibility Bites are more than just tips; they represent a valuable resource for anyone committed to enhancing accessibility in their work or community. By breaking down complex topics into manageable pieces, we aim to cultivate a culture of inclusion and awareness that resonates across various sectors. As we launch this exciting series, we invite you to engage with our Accessibility Bites and share them within your networks. Each article will serve as a stepping stone toward building a more inclusive environment, and your participation is essential in this collective effort. Whether you are a designer, developer, educator, or advocate, these bite-sized resources are crafted to empower you to make a meaningful difference in your community. Together, let’s embrace these insights and take significant strides toward a more accessible world — one article at a time. Stay tuned for our first Accessibility Bite, and let’s embark on this journey toward inclusivity together!</p><h4>More reads:</h4><ol><li><a href="https://medium.com/@roy11manisha/can-we-skip-non-text-content-ee5461cf9813">Can we skip non-text content?</a></li><li><a href="https://medium.com/p/dda3072bff97?postPublishedType=initial">Wondering where is your heading?</a></li><li><a href="https://medium.com/p/4a6ea19338f6?postPublishedType=initial">Why my speech only user struggling to perform actions?</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1e5c16dbb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest way to add a collapsible header to an iOS app]]></title>
            <link>https://medium.com/@roy11manisha/the-simplest-way-to-add-a-collapsible-header-to-an-ios-app-a7cc7e72101a?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7cc7e72101a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[collapsible-header]]></category>
            <category><![CDATA[header]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 08:44:07 GMT</pubDate>
            <atom:updated>2023-08-02T08:44:07.535Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using UITableView and UICollectionView with a custom header</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DfrdGTLXrgf6q_yA" /><figcaption>Photo by <a href="https://unsplash.com/@zanilic?utm_source=medium&amp;utm_medium=referral">Zan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>An expandable/collapsable header or scrollable top view is one of the most commonly seen features in the latest mobile apps. Still, unfortunately, iOS doesn’t have in-built support for that. Here, third-party libraries/frameworks are saviours but debugging &amp; customizing huge chunks of code becomes a big task for developers.</p><p>In this article, we will create a reusable component with minimal coding that can be customized as needed. The following image shows what we’ll achieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20w3p2v9AftgtozbTT0uCg.png" /><figcaption>Header collapsed and is partially visible at the top.</figcaption></figure><h3>Project setup with UITableview</h3><p>Create a new project and name it as MyApp. Add one UITableView inside the Main.storyboard as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bphKL-IeSV4XOafNOq2M_A.png" /><figcaption>Initial project setup</figcaption></figure><p>After adding UITableView follow these steps to complete the initial UI setup on the storyboard:</p><ul><li>Use Superview instead of Safe Area while creating constraints for table-view.</li><li>Add one static cell by giving an <em>identifier</em> as a <strong>cell.</strong></li><li>Change its <em>style</em> to <strong>basic</strong>.</li><li>Change the label’s <em>font size</em> to <strong>25</strong>.</li><li>Create an outlet for UITableView and name it as <strong>tableView</strong>. Also, create a reference outlet for UITableView’s DataSource.</li></ul><p>ViewController on the storyboard will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjciI_QW9Vr5OIVFHRVX2g.png" /><figcaption>Table view with a static cell</figcaption></figure><p>Now let’s start populating the table view with data. Go to ViewController.swift and add the following code.</p><pre>extension ViewController: UITableViewDataSource {<br>  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>    20<br>  }<br><br>  func tableView(_ tableView: UITableView, <br>    cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    let cell = tableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath)<br>    cell.textLabel?.text = &quot;Row \(indexPath.row)&quot;<br>    return cell<br>  }<br>}</pre><blockquote>This article has used native components and features provided by <a href="https://developer.apple.com/documentation/uikit/views_and_controls/table_views">Apple</a>.</blockquote><p>The following result can be observed when we run the app. Here, we have simply loaded the table view with rows which display the given title. Each row has a unique identifier <em>cell</em> which we set on the storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UvasoZGQkO_W-4zN6jRUCA.gif" /><figcaption>Table view loaded with 20 rows</figcaption></figure><h4>Adding header</h4><p>Go back to the storyboard and follow these steps to add a header inside the table:</p><ul><li>Add UIView above UITableViewCell referred to as headerView.</li><li>Change its color to black.</li><li>Mark Clips to bound as checked.</li><li>Set its height to 264.</li><li>Add one UIView as a subview. Create one outlet for it by naming curvedHeaderView.</li><li>Set curvedHeaderView’s corner radius as 26 pixels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rq9LrRwOGeTKcBpZFV8k2w.png" /><figcaption>Header view inside a table view</figcaption></figure><p>Change table-view’s Content Insets to <strong>never </strong>for removing white space above the black view</p><h4>Sticking the header at the top</h4><p>After running the app, we will observe that curvedHeaderView is also getting scrolled outside the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*V0oZGphjljKgLQLm1l7scA.gif" /><figcaption>Header view getting scrolled with table rows</figcaption></figure><p>We want curvedHeaderView to get fixed at the top of the screen. Follow these steps to create a custom view that will act as collapsed header view:</p><ul><li>Add one UIView above table-view named customNavView</li><li>Align its top, left, and right to table-view and give height as 110.</li><li>Mark Clips to bound as checked.</li><li>Add one UILabel named navTitleLabel.</li><li>Add constraints to navTitleLabel as per need.</li><li>Change the font color of navTitleLabel to white and hide it.</li><li>Add one UIView similar to curvedHeaderView and name it curvedNavView.</li><li>Set curvedHeaderView’s corner radius as 26 pixels and hide it as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9Z3P7YSlFVoGZd5E3XKjw.png" /><figcaption>Constraints on curvedNavView</figcaption></figure><p>Go back to ViewController.swift and create two variables:</p><pre>var titleHeight: CGFloat = 0.0<br>let titleText = “Expand/Collapse”</pre><p>Set titleText to navTitleLabel and to the first row’s label:</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>…<br>  if indexPath.row == 0 {<br>    cell.textLabel?.text = titleText<br>    titleHeight = cell.textLabel?.bounds.height ?? 0<br>  }<br>…</pre><p>Next, we will confirm to UIScrollViewDelegate protocol which has scrollViewDidScroll(_) method. We also need to confirm to UITableViewDelegate, without which table view won&#39;t call scrollViewDidScroll(_) method.</p><pre>extension ViewController: UITableViewDelegate, UIScrollViewDelegate {<br>  func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>    let maxHeight = 150.0<br>    let hide = scrollView.contentOffset.y &lt;= maxHeight<br>    curvedNavView.isHidden = hide<br>    navTitleLabel.isHidden = scrollView.contentOffset.y &lt;= (maxHeight + titleHeight)<br>    customNavView.backgroundColor = hide ? .clear : .black<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Pgij09kZdHuHVqNUSRCXHQ.gif" /><figcaption>The first row’s title is shown at the top of the screen on the header view collapse</figcaption></figure><h4>Tips</h4><ul><li>Customize headerView as per app needs, such as adding images, labels, etc...</li><li>Simply print contentOffset till the point where the header needs to be fixed and take y as maxHeight.</li><li>If you face some issues with the multiline label, then reload the table-view in viewDidAppear(_).</li></ul><h4>Conclusion</h4><p>In this article, we have created a custom header view for UITableView which gets attached at the top on its scroll. In the same way, we can have it for UICollectionView as well, simply add headerView as a subview of UICollectionReusableView and we are good to go.</p><p><strong>Do check out my other articles on </strong><a href="https://medium.com/globant/mobile-ai-introduction-global-market-forecast-38d89eeef10f"><strong>Mobile-AI</strong></a><strong> and </strong><a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e"><strong>SwiftUI</strong></a><strong>.</strong></p><blockquote><em>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7cc7e72101a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript in iOS Native App]]></title>
            <link>https://medium.com/@roy11manisha/javascript-in-ios-native-app-223aa17428f3?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/223aa17428f3</guid>
            <category><![CDATA[wkwebview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 06:12:18 GMT</pubDate>
            <atom:updated>2023-06-05T06:12:18.813Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial for beginners</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4oxrLWDW1_HaQd3u" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The software development evolution requires advanced interaction between mobile apps and remotely/locally located data that can be loaded inside web views. This speed up the development process, and some delicate JavaScript features can be integrated into mobile apps.</p><p>If you are a beginner like me who doesn’t know much about HTML tags and JavaScript, then don’t worry; this tutorial will help you to have two-way interactions between a mobile app and WKWebViewand most importantly, it builds your confidence in JavaScript.</p><h3>Create a project</h3><p>Create a new Xcode project and name it as <strong>WebInteraction</strong>. Create a new Cocoa Touch File named <strong>WebViewController</strong> and set the subclass as UIViewController. After file creation, follow these steps:</p><ol><li>Open WebViewController and add import WebKit</li><li>Add these lines inside the class definition @IBOutlet var webView: WKWebView!</li><li>Go to Main.storyboard, add WKWebView, and connect it to the <strong>webView</strong> as shown below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA7ev3iSFGZ-5amlDKy_dQ.png" /><figcaption>Initial project setup</figcaption></figure><h4>Create HTML file</h4><p>Our <strong>webView</strong> has been created, but we also need one HTML file to load the contents inside it. Open Terminal and run these commands to create a fresh HTML file:</p><pre>cd &lt;Path to Xcode project folder&gt;<br>touch SampleJavaScript.html</pre><p>After adding this newly created HTML file inside the project target, write the following code inside SampleJavaScript.html :</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;button&gt;First Button&lt;/button&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here, we have added one button titled “First Button”<em>.</em></p><h4>Load HTML file inside web-view</h4><p>Open WebViewController.swift and add the following code block inside viewDidLoad() :</p><pre>guard let url = Bundle.main.url(/service/forresource: %E2%80%9CSampleJavaScript%E2%80%9D, withExtension: %E2%80%9Chtml%E2%80%9D, subdirectory: %E2%80%9C%E2%80%9D) else {return}<br>let request = URLRequest(url: url)<br>webView.load(request)</pre><p>If SampleJavaScript.html is available inside the main Bundle , then we create one URLRequest and load this request to <strong>webView,</strong> which is of type WKWebView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5UBCvgG1REwAerLSJCW0Q.png" /><figcaption>The app loaded with an HTML file</figcaption></figure><p>After running the app, we can see the “First Button” inside the web view. This button is tappable but doesn’t perform any action at this moment.</p><h4>JavaScript for creating a paragraph</h4><p>Let’s add some action to the “First Button<em>”</em> so that it will create one paragraph whenever a user taps on it. For that open SampleJavaScript.html and write a script to create and define our expected behavior.</p><p>Please note that scripts can be written inside the &lt;head&gt;, inside the &lt;body&gt; or both but it is advisable to add them at the bottom of &lt;body&gt; as it improves the display speed and also it’s easier for developers to look for. In this article, we will add scripts at the bottom of the &lt;body&gt;.</p><pre>&lt;script&gt;<br>  function createPara() {<br>    document.getElementById(“paralog”).innerHTML = “Creating paragraph”<br>  }<br>&lt;/script&gt;</pre><p>In HTML, we use the &lt;script&gt; tag to create a script. We want the script to be called on button click; hence we have included it inside a function named <em>createPara()</em>. Let’s first attach this function to the “First Button”.</p><pre>&lt;button onclick=”createPara()”&gt;First Button&lt;/button&gt;</pre><p>We have simply added an onclick inside button tag in such a way that it will call <em>createPara()</em> whenever the user taps on the button. If you run the app and tap the button, nothing will happen. Let’s learn how JavaScript works here and what a solution is to make it workable.</p><pre>document.getElementById(“paralog”).innerHTML += “Creating paragraph”</pre><p>JavaScript is looking for the element with tag <em>paralog</em> but our HTML document has none. Add this above &lt;script&gt; tag.</p><pre>&lt;p id=”paralog”&gt;&lt;/p&gt;</pre><p>We have used &lt;p&gt; as we want to create one paragraph. Now whenever <em>createPara()</em> is called, it looks for this element and updates its innerHTML by appending “Creating paragraph<em>”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BO5awvUfuoa-8DBoFcjRXA.gif" /><figcaption>Paragraph creation</figcaption></figure><p>If you wish to add a new line before adding the new texts, then simply add &lt;br&gt; tag as:</p><pre>document.getElementById(“paralog”).innerHTML += “&lt;br&gt;” + “Creating paragraph”</pre><p>Just run the app and see the magic. Congratulations!! You have written your first JavaScript that too in the easiest way.</p><h3>Fetching data from the web to the app</h3><p>Till now, we have learned how we can write JavaScript, which gets invoked on the user’s action. Let’s move to make our HTML file more interactable in such a way that it sends the user’s action to UIViewController.</p><h4><strong>Add script receiver inside a Swift file</strong></h4><p>Open WebViewController.swift and follow these steps:</p><ol><li>Add this configuration before loading URLRequest to <strong>webView</strong>. Here, we are adding a script message handler to <strong>webView</strong>. The name of the script message handler is <em>toMobile.</em></li></ol><pre>webView.configuration.userContentController.add(self, name: “toMobile”)</pre><p>2. The above line will throw an error as Argument type ‘WebViewController’ does not conform to the expected type ‘WKScriptMessageHandler’. To fix the error, we need to add the following code block.</p><pre>extension WebViewController: WKScriptMessageHandler {<br>  func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {<br>  }<br>}</pre><p>This delegate method will be called whenever a script is run with the name <em>toMobile</em>.</p><h4><strong>Add script inside HTML file</strong></h4><p>Our Swift file is ready to receive the message through a script from the HTML, but the script is yet not written. Let’s move to SampleJavaScript.html and add a script there.</p><ul><li>Add a new button with the title “To Mobile” which will call the function scriptToMobile()</li></ul><pre>&lt;button onclick=”scriptToMobile()”&gt;To Mobile&lt;/button&gt;</pre><ul><li>Define scriptToMobile() as:</li></ul><pre>&lt;script&gt;<br>  function scriptToMobile() {<br>    webkit.messageHandlers.toMobile.postMessage(“script from web to view controller”);<br>  }<br>&lt;/script&gt;</pre><ul><li>webkit.messageHandlers represent that script is written for the iOS app.</li><li>toMobile is the script name with which we have configured WKWebView to receive the user’s action.</li><li>postMessage sends a trigger to a receiver that it has published some message.</li></ul><h4><strong>Access script message inside the Swift file</strong></h4><p>Our main aim of setting communication between Swift file and HTML file is achieved. It will be more interesting to decode the message sent by a script. Update the WKScriptMessageHandler delegate method as follows:</p><pre>func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {<br>  if message.name == “toMobile” {<br>    print(message.body)<br>  }<br>}</pre><p>The message.name gives the name of a script, whereas the message.body is an actual message sent by a script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HWBss2TRdOEUvfwcOYzhMA.gif" /><figcaption>Web message inside Xcode console</figcaption></figure><p>We can see that on the “To Mobile” click script message is printed to the Xcode console. Instead of printing the message, we can perform any other desired operation as well, like doing some Database operation or going to some other screen.</p><h3>Fetching data from the app to the web</h3><p>Till now, we have learned how mobile apps interact with the web with the help of scripts. Now we will see how mobile apps can write JavaScript in such a way that it sends data from Swift files and how HTML files handle it.</p><h4><strong>Add script inside a Swift file</strong></h4><p>We will track the number of taps on the button written inside HTML. The Swift file will handle the count.</p><ul><li>Let’s first declare one variable as var htmlButtonCount = 0</li><li>Add one more configuration to <strong>webView</strong> for handling script message</li></ul><pre>webView.configuration.userContentController.add(self, name: “fromMobile”)</pre><ul><li>Edit WKScriptMessageHandler delegate method as</li></ul><pre>func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {<br>  ..<br>  } else if message.name == “fromMobile” {<br>    htmlButtonCount += 1<br>    self.webView?.evaluateJavaScript(“webkit.messageHandlers.fromMobile.onMessage(‘User taps \(htmlButtonCount)’)”)<br>  }<br>}</pre><p>Here, we are incrementing htmlButtonCount whenever we receive a script message named fromMobile. WKWebView has two methods to evaluate JavaScript. One of them is open func evaluateJavaScript(_ javaScriptString: String) async throws -&gt; Any which is used above. The only required parameter is javaScriptString which is written as:</p><pre>“webkit.messageHandlers.fromMobile.onMessage(‘User taps \(htmlButtonCount)’)”</pre><ul><li>webkit.messageHandlers represent that script is written for the iOS app.</li><li>fromMobile is the script name with which we have configured our WKWebView to receive the user’s action.</li><li>Swift uses the onMessage event to send button taps to an HTML file.</li></ul><h4><strong>Script handler inside HTML file</strong></h4><p>Let’s first add one more button in the HTML file to achieve our functionality:</p><pre> &lt;button onclick=&quot;scriptFromMobile()&quot; id=&quot;userClickLog&quot;&gt;From Mobile&lt;/button&gt;</pre><p><em>scriptFromMobile()</em> function will be defined as:</p><pre>&lt;script&gt;<br>  function scriptFromMobile() {<br>    webkit.messageHandlers.fromMobile.postMessage(“getUserCount”);<br><br>    webkit.messageHandlers.fromMobile.onMessage = (msg) =&gt; {<br>      document.getElementById(&quot;userClickLog&quot;).innerHTML = &quot;From Mobile&quot; + &quot;&lt;br&gt;&quot; + msg    <br>    }<br>  }<br>&lt;/script&gt;</pre><ul><li>Here, we have one script to post a message with an identifier <em>fromMobile</em>. This message is received by the WKScriptMessageHandler delegate function and a previously defined operation is performed by a Swift file to send the user’s count.</li><li>The next script waits till it receives the onMessage action with the identifier <em>fromMobile</em>.</li><li>Once the onMessage action is received, the third and the last script of the function is executed. This script writes down the Swift file message to the element with the identifier <em>userClickLog</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*GkADEVhPwDrSFct0NSvVZw.gif" /><figcaption>Data from mobile to web</figcaption></figure><p>Here, whenever a user taps on the “From Mobile” button of the HTML file, the <em>htmlButtonCount</em> variable of the Swift file gets incremented. The Swift file has a JavaScript to send this count to an HTML file.</p><h3>Keynotes:</h3><p>These are the keynote from this article that will help you for future exploration as well.</p><h4><strong>Native App</strong></h4><ul><li>The WKWebView instance referred to as <strong>webView</strong> should be configured with userContentController with the unique name used for script interactions.</li><li>The <strong>webView</strong> can be configured with any number of userContentController.</li><li>The <strong>webView</strong> should confirm to WKScriptMessageHandler delegate function userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)</li><li>Use the evaluateJavaScript function provided by WKWebView for writing the script from iOS native app to an HTML file.</li><li>Use webkit.messageHandlers.&lt;nameOfConfiguration&gt; for writing scripts for iOS native apps.</li></ul><h4><strong>Web</strong></h4><ul><li>It’s good practice to write scripts at the bottom of the &lt;body&gt; tag.</li><li>Use postMessage for sending messages/data to a native app.</li><li>Use onMessage to receive messages/data from a native app.</li><li>Always call postMessage to invoke onMessage events from a native app.</li></ul><h3>Conclusion</h3><p>Being a beginner may fear us to write JavaScript that too if you want to interact with iOS Native App. This article used very basic HTML tags and concepts of JavaScript. First, we updated the web without a script then we added scripts for communication between both ends.</p><p><strong>Do check out my other articles on </strong><a href="https://medium.com/globant/mobile-ai-introduction-global-market-forecast-38d89eeef10f"><strong>Mobile-AI</strong></a><strong> and </strong><a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e"><strong>SwiftUI</strong></a><strong>.</strong></p><blockquote><em>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223aa17428f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI | Animation | Tic-Tac-Toe Game]]></title>
            <link>https://medium.com/@roy11manisha/swiftui-animation-tic-tac-toe-game-4ffe37aba0b8?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ffe37aba0b8</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[spinning]]></category>
            <category><![CDATA[dazzling]]></category>
            <category><![CDATA[tic-tac-toe-game]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 13:44:41 GMT</pubDate>
            <atom:updated>2022-09-21T13:44:41.132Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 8 of the Tic-Tac-Toe Game <a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e">series</a>. Till now we have created 3 rounds of the tic-tac-toe game which decides the winner of each round and ends the game once all 3 rounds are played. We have also included some animation in our game. In this article, we will learn how smoothly SwiftUI works.</p><p>First, go through some of the basic yet useful animations provided by SwiftUI and accordingly announces the game winner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7jYMY7u32Skr6k5Yq0P6g.png" /><figcaption>The current player highlighted by scaling</figcaption></figure><p>This is the first animation we see in the game where the current player gets highlighted by scaling it, for that SwiftUI provides <em>scaleEffect(_)</em>. To make the transition smooth we have added default animation to it. SwiftUI provides the following animations which are also in swift:</p><ul><li>default</li><li>easeInOut</li><li>easeIn</li><li>easeOut</li><li>linear</li></ul><p>Let’s use the same animation effect to zoom out grids selected by the player when their turn arrives, which will help them to decide their next move. Go to <em>CheckerboardGrid</em> struct and jump to the line where we draw X or O.</p><pre>if self.gridDetail.player == 1 {<br>   Circle()<br>      .stroke(PlayerInfo.player1.getPlayerColor(), lineWidth: 5)<br>      .frame(width: 20, height: 20, alignment: .center)<br>      .scaleEffect(self.settings.currentPlayer == 1 ? 1.5 : 1)<br>      .animation(.default, value: self.settings.currentPlayer == 1)<br>} else {<br>   XMarkView()<br>      .stroke(PlayerInfo.player2.getPlayerColor(), lineWidth: 5)<br>      .frame(width: 20, height: 20, alignment: .center)<br>      .scaleEffect(self.settings.currentPlayer == 2 ? 1.5 : 1)<br>      .animation(.default, value: self.settings.currentPlayer == 2)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HIik3Xk8POg1IysfzzKd2Q.gif" /></figure><p>Isn’t it WOW that just 2 lines of code have changed the whole look and feel!!</p><p>The next animation we have on this screen is this spinning baton between player names. For spinning the baton we have rotationEffect(_) provided by SwiftUI.</p><blockquote><em>rotationEffect(_)</em> requires an animation modifier to be added to make it work, unlike <em>scaleEffect(_) </em>which does the job without it.</blockquote><pre>struct BatonView: View {<br>   @State private var isBatonSpinning = false<br>   var body: some View {<br>      Rectangle()<br>         .frame(width: 40, height: 5)<br>         .foregroundColor(.gray)<br>         .shadow(radius: 10)<br>         .padding(30)<br>         .rotationEffect(Angle(degrees: isBatonSpinning ? 360 : 0))<br>         .animation(.default, value: isBatonSpinning)<br>         .onAppear() {<br>            self.isBatonSpinning = true<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {<br>               self.isBatonSpinning = false<br>...</pre><p>This code will rotate a gray color rectangle to 360 only once. To continuously rotate it for 2 seconds, just modify it as:</p><pre>...<br>.animation(.default.repeatForever(), value: isBatonSpinning)<br>...</pre><p>The baton is spinning back and forth for 2 seconds but we need to rotate it in one direction only, for that just off the <em>autoreverses</em> which is on by default. After running the code, we can see the baton continuously spinning in one direction for 2 seconds but after that, some random animation can be observed too. To resolve it we just need to turn off <em>repeatForever</em> once <em>isBatonSpinning</em> is turned off.</p><pre>extension Animation {<br>   func `repeat`(while expression: Bool, autoreverses: Bool = false) -&gt; Animation {<br>      if expression {<br>         return self.repeatForever(autoreverses: autoreverses)<br>      } else {<br>         return self<br>      }<br>   }<br>}</pre><pre>//BatonView<br>...<br>.animation(.default.repeat(while: isBatonSpinning), value: isBatonSpinning)<br>...</pre><p>These are some of the basic animations provided by SwiftUI that we have used in the game. Let’s move to the next part of the article where we will create advanced animation for announcing the winner of the game. But before that, we will add some business logic inside GameSettings.</p><pre>var gameWinMsg: String {<br>   let player1Won = rounds.filter({$0.winnerPlayer == PlayerInfo.player1.rawValue}).count</pre><pre>   let player2Won = rounds.filter({$0.winnerPlayer == PlayerInfo.player2.rawValue}).count</pre><pre>   if player1Won &gt; player2Won {<br>      return “Player \(PlayerInfo.player1.rawValue) won game!!”<br>   }</pre><pre>   if player1Won &lt; player2Won {<br>      return “Player \(PlayerInfo.player2.rawValue) won game!!”<br>   }</pre><pre>   return “It’s a tie!!”<br>}</pre><p>Just add the above code inside <em>GameSettings</em> and create a new file named <em>EndGameView </em>where we will animate this<em> gameWinMsg</em> string. Before that, we will create dazzling animation for it.</p><pre>struct DazzlingStringAnimatiom: AnimatableModifier {<br>   let string: String<br>   var flag: Double</pre><pre>   var animatableData: Double {<br>      get { flag }<br>      set { flag = newValue }<br>   }<br>...</pre><ul><li>AnimatableModifier: reusable modifier for animation.</li><li>animatableData: mandatory property to have for an animation to take place.</li><li>string: enumerate through each character of this to dazzling effect on it.</li><li>flag: sent from parent which makes the views redraw.</li></ul><pre>...<br>func body(content: Content) -&gt; some View {<br>   HStack(spacing: 0) {<br>      ForEach(Array(string.enumerated()), id: \.0) { (index, character) in<br>         Text(String(character))<br>            .bold()<br>            .font(.largeTitle)<br>            .foregroundColor(Color.init(red: Double.random(in: 0..&lt;1), green: Double.random(in: 0..&lt;1), blue: Double.random(in: 0..&lt;1)))<br>      }<br>   }<br>}</pre><ul><li>We are creating a Text view for each character of a string and horizontally aligning them.</li><li>Foreground color is applied randomly which creates a dazzling effect.</li></ul><p>Open DashboardView where WinnerListView is added. Add this EndGameView as the first view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yABDz3sEtIJV-EiGCNhsdw.gif" /></figure><p>Here, you may have observed reset game functionality is added as well. Let’s go through them as well. Open DashboardView where WinnerListView is added and update it as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkJeppwAlVAUuz7QX2pFeQ.png" /></figure><ul><li>If all round is played then we are showing EndGameView.</li><li>After showing WinnerListView, again we decide whether we want to show “Play Game” or “Reset Game”.</li><li>“Play Game” functioning as the previous one.</li><li>“Reset Game”, reset the game on tap of it and keeps the player on same screen.</li></ul><p>To reset the game, open GameSettings and add resetGame() as:</p><pre>func resetGame() {<br>resetRoundSettings()<br>setUpRounds()<br>currentRound = 0<br>}</pre><pre>func resetRoundSettings() {<br>currentPlayer = 0<br>isRoundEnded = false<br>noOfStrikes = 0<br>roundWinner = 0<br>setupGridDetails()<br>}</pre><p><strong>Do check out my other articles in this series:</strong></p><p><a href="https://medium.com/@roy11manisha/swiftui-text-view-styling-lets-play-tic-tac-toe-game-7987909584fb">Text view styling</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-tic-tac-toe-game-button-154a35997bc">Button</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-navigation-tic-tac-toe-game-d05d52cf4636">Navigation</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-shapes-tic-tac-toe-game-376073b11102">Shapes</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-drawing-tic-tac-toe-game-71fae0d46381">Drawing</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-data-flow-tic-tac-toe-game-bace4fbeb3ac">Data Flow</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-list-tic-tac-toe-game-8ad7aaa4050]/==">List</a></p><blockquote>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ffe37aba0b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI: Complete guide with Tic-Tac-Toe Game]]></title>
            <link>https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2fea4f980e</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[series]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[tic-tac-toe-game]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Fri, 05 Aug 2022 12:21:30 GMT</pubDate>
            <atom:updated>2022-10-03T06:08:21.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1PYUiTEjRBUhdi27mNSCOg.gif" /></figure><p>If you are eager to learn SwiftUI and want some in-hand experience on how a complete app can be developed by purely using SwiftUI then check out these articles where the tic-tac-toe game is developed using SwiftUI. Each article gives an in-depth knowledge of SwiftUI components and features.</p><p><a href="https://medium.com/globant/dive-into-amazing-world-of-swiftui-f35a25c5e9ce">Introduction</a></p><p><a href="https://medium.com/globant/swiftui-property-wrappers-explained-in-simplest-way-28cb580c6408">Property wrappers</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-text-view-styling-lets-play-tic-tac-toe-game-7987909584fb">Text view styling</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-tic-tac-toe-game-button-154a35997bc">Button</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-navigation-tic-tac-toe-game-d05d52cf4636">Navigation</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-shapes-tic-tac-toe-game-376073b11102">Shapes</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-drawing-tic-tac-toe-game-71fae0d46381">Drawing</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-data-flow-tic-tac-toe-game-bace4fbeb3ac">Data Flow</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-list-tic-tac-toe-game-8ad7aaa4050">List</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-animation-tic-tac-toe-game-4ffe37aba0b8">Animation</a></p><blockquote><em>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2fea4f980e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e">SwiftUI: Complete guide with Tic-Tac-Toe Game</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI | List | Tic-Tac-Toe Game]]></title>
            <link>https://medium.com/globant/swiftui-list-tic-tac-toe-game-8ad7aaa4050?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad7aaa4050</guid>
            <category><![CDATA[tic-tac-toe-game]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Fri, 05 Aug 2022 12:07:52 GMT</pubDate>
            <atom:updated>2022-09-22T13:57:39.220Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 7 of the Tic-Tac-Toe Game <a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e">series</a>. Till now we created a one-round tic-tac-toe game for deciding the winner. Let’s make it 3 rounds game and the winner will be the one who has won a maximum number of rounds. Also, we will explore the List view for designing the score table to show who won which round.</p><p>Create a new ObservableObject class and name it RoundWinnerInfo. We need only two properties to be tracked, the round and that round’s winner. Make it Identifiable as well to iterate through instances of this class for designing List rows.</p><pre>class RoundWinnerInfo: Identifiable, ObservableObject {<br>   var id = UUID()<br>   var round: Int<br>   @Published var winnerPlayer: Int = -1<br>   init(round: Int) {<br>      self.round = round<br>   }<br>}</pre><pre>//Update GameSettings</pre><pre>@State var rounds: [RoundWinnerInfo] = []</pre><pre>init() {<br>   rounds = [RoundWinnerInfo(round: 1), RoundWinnerInfo(round: 2), RoundWinnerInfo(round: 3)]<br>   setupGridDetails()<br>}</pre><p>We will use <em>rounds</em> for designing our score table. Create a new SwiftUI file and name it WinnerListView. Create one new struct named WinnerListRow which will be rows of the List/Table view.</p><pre>@Binding var round: RoundWinnerInfo</pre><p>WinnerListRow will have one instance of RoundWinnerInfo which will be bound with the all rounds array of @State property wrapper type. Each row will have three columns: round number, player 1 and player 2 details.</p><pre>var body: some View {<br>   HStack {<br>      Text(“\(round.round)”)<br>         .bold()<br>         .modifier(WinnerListRowModifier())<br>      if round.winnerPlayer != -1 {<br>         if round.winnerPlayer == 1 {<br>            Image(systemName: “checkmark”)<br>               .modifier(WinnerListRowModifier())<br>         } else {<br>           Text(“ — “).modifier(WinnerListRowModifier())<br>         }</pre><pre>         if round.winnerPlayer == 2 {<br>            Image(systemName: “checkmark”)<br>               .modifier(WinnerListRowModifier())<br>         } else {<br>            Text(“ — “).modifier(WinnerListRowModifier())<br>         }<br>      }<br>   }.multilineTextAlignment(.center)<br>}</pre><p>If a round is played then we are showing a checkmark to the winner player and — is shown to the other player. A structure of type ViewModifier can be created and modifiers can be clubbed there to use it with multiple views, WinnerListRowModifier is an example of such a case.</p><pre>struct WinnerListRowModifier: ViewModifier {<br>   func body(content: Content) -&gt; some View {<br>      content<br>         .frame(width: 80, height: 50, alignment: .center)<br>   }<br>}</pre><p>Rows are ready but it will be good to have headers as well to complete the look of the score table.</p><pre>struct WinnerListHeader: View {<br>   var body: some View {<br>      HStack {<br>         Text(“Round”).modifier(WinnerListRowModifier())<br>         Text(“Player 1”).modifier(WinnerListRowModifier())<br>         Text(“Player 2”).modifier(WinnerListRowModifier())<br>         Spacer()<br>      }.multilineTextAlignment(.center)<br>   }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7vZUe6fMOCGO9zsJC0kiw.png" /></figure><p>We can see that there are some glitches in the UI. We don’t need this grey color produced by List view. At this moment SwiftUI doesn’t have an inbuilt modifier for changing/removing this color but we can use Swift code for handling the table appearance. Add this modifier on List view:</p><pre>...<br>.onAppear{<br>   UITableView.appearance().backgroundColor = .clear<br>}.padding(EdgeInsets(top: -30, leading: 0, bottom: 0, trailing: 0))<br>...</pre><p>Hold on!! Everything will be white on the screen. Let’s change the row color to light grey color to distinguish it from the parent view.</p><pre>WinnerListRow(round: round).listRowBackground(settings.disabledColor)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aAVaXCZ0I4CG6IJuV2WH0w.png" /><figcaption>Score table with dummy data</figcaption></figure><p>Our UI is ready but we need to update the winner of each round to achieve the above result. For that we will add more properties to GameSettings:</p><pre>var currentRound = 0</pre><pre>func setCurrentRound() {<br>   currentRound = rounds.filter({$0.winnerPlayer == -1}).first?.round ?? 0<br>}</pre><pre>func updateRoundDetails() {<br>   var _ = rounds.filter { round in<br>      if round.round == currentRound {<br>         round.winnerPlayer = winner<br>      }<br>      return true<br>   }<br>}</pre><p>setCurrentRound() will be called on onAppear() of GameScreen. And whenever a winner is decided or the game is ended with a tie, we will call updateRoundDetails() for setting the winner of the current round.</p><p>We need to restrict the players to play after 3 rounds. For that, we will add a new property isAllRoundPlayed inside GameSettings which will return true or false as:</p><pre>var isAllRoundPlayed: Bool {<br>   return rounds.filter({$0.winnerPlayer != -1}).count == 3<br>}</pre><p>This flag will be used on the “Play Game” button to decide the disability as:</p><pre>...<br>.disabled(settings.isAllRoundPlayed)<br>...</pre><p>So whenever a player plays all three rounds, this button becomes greyed out and no operation will be performed. but if you go back to DashboardView and come back again then all the data will be there. We need to reset GameSettings at some point in the app.</p><p>PlayButtonView’s onDisappear() gets called whenever a new view is pushed or it gets popped, so resetting the setting here is not a good choice. Another option is to use DashboardView’s onAppear() as it will be called when PlayButtonView is popped.</p><pre>...<br>.onAppear(){<br>   settings.resetGame()<br>}<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wQ_gG_2urNsVifHPvD3R2g.gif" /></figure><p><strong>Do check out my other articles in this series:</strong></p><p><a href="https://medium.com/@roy11manisha/swiftui-text-view-styling-lets-play-tic-tac-toe-game-7987909584fb">Text view styling</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-tic-tac-toe-game-button-154a35997bc">Button</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-navigation-tic-tac-toe-game-d05d52cf4636">Navigation</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-shapes-tic-tac-toe-game-376073b11102">Shapes</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-drawing-tic-tac-toe-game-71fae0d46381">Drawing</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-data-flow-tic-tac-toe-game-bace4fbeb3ac">Data Flow</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-animation-tic-tac-toe-game-4ffe37aba0b8">Animation</a></p><blockquote><em>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad7aaa4050" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/swiftui-list-tic-tac-toe-game-8ad7aaa4050">SwiftUI | List | Tic-Tac-Toe Game</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI | Data flow | Tic-Tac-Toe Game]]></title>
            <link>https://medium.com/globant/swiftui-data-flow-tic-tac-toe-game-bace4fbeb3ac?source=rss-5ba78b73ee00------2</link>
            <guid isPermaLink="false">https://medium.com/p/bace4fbeb3ac</guid>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[tic-tac-toe-game]]></category>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Manisha Roy]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 13:32:41 GMT</pubDate>
            <atom:updated>2022-09-22T13:57:44.163Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 6 of the Tic-Tac-Toe Game <a href="https://medium.com/globant/swiftui-complete-guide-with-tic-tac-toe-game-ae2fea4f980e">series</a>. In this article, we will learn how data flows in SwiftUI and add some rules to our game, Tic-tac-toe. SwiftUI usage <a href="https://medium.com/globant/swiftui-property-wrappers-explained-in-simplest-way-28cb580c6408">property wrapper</a> for passing data and managing their states throughout the app.</p><p>The first rule checks whether the game has ended or not. The game will end if all the grids have been selected or if the winner is announced. We will first focus on grid selection, for that we have one flag <em>noOfStrikes </em>inside<em> GameSettings</em> which tracks the number of taps by both the players.</p><blockquote>Please refer SwiftUI <a href="https://medium.com/@roy11manisha/swiftui-drawing-tic-tac-toe-game-71fae0d46381">Drawing</a> article to access the latest code.</blockquote><p>Jump back to <em>onTapGesture</em> of Rectangle inside MatrixBlock view. Here we will increment <em>noOfStrikes</em> just after updating gridDetail:</p><pre>...<br>self.gridDetail.player = self.settings.currentPlayer</pre><pre>settings.noOfStrikes += 1<br>...</pre><p>We have one more flag isGameEnded inside GameSettings which publishes its update to observing views. Add one function setGameEnded inside GameSettings which will update this flag.</p><pre>func setGameEnded() {<br>   if noOfStrikes == 9 {<br>      isGameEnded = true<br>   }<br>}</pre><p>We have 9 grids on our checkerboard that’s why 9 strikes will end the game. We will use isGameEnded publisher’s state to show EndGameView below the checkerboard.</p><p>Create a new SwiftUI file naming it EndGameView where just replace the content of Text view with <strong>Game ended. </strong>The code will look like this:</p><pre>struct EndGameView: View {<br>   var body: some View {<br>      Text(“Game ended”)<br>         .multilineTextAlignment(.center)<br>         .font(.largeTitle)<br>   }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zrd0OEVuZ1wzq9Zwbzs2UA.png" /></figure><p>The game has ended but the winner is yet not decided. The Tic-tac-toe game has these rules for deciding the winner:</p><ul><li>The same player played in a single line.</li><li>The same player played in a single column.</li><li>The same player played diagonally.</li></ul><p>In the above screenshot, we can see that player 2 is a winner as s/he has marked X diagonally.</p><p>To decide the winner, we need to track each grid on which player has played. MatrixBlock has GridDetail which stores enough details of the grid for deciding the winner. but the problem is that this individual GridDetail cannot be tracked for implementing the above rules as MatrixGrids is drawing straightforward 3*3 MatrixBlock using <em>ForEach. </em>Let&#39;s first club the GridDetail instances in one place so that their data can be accessed easily and will always be in sync.</p><p>Create one new struct RowGridDetails which will store a collection of GridDetail for a single row. We will save this RowGridDetails instance inside GameSettings as this 3*3 checkerboard belongs to the game setting.</p><pre>struct RowGridDetails {<br>   var grids: [GridDetail]<br>}</pre><pre>class GameSettings: ObservableObject {<br>   var gridDetails: [RowGridDetails] = [<br>      RowGridDetails(grids: [GridDetail(), GridDetail(), GridDetail()]),</pre><pre>      RowGridDetails(grids: [GridDetail(), GridDetail(), GridDetail()]),</pre><pre>      RowGridDetails(grids: [GridDetail(), GridDetail(), GridDetail()])]<br>...</pre><blockquote>This will allow us to have a checkerboard n*n or n*m size.</blockquote><p>Now iterate through this gridDetails for creating MatrixGrids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zv2AvKCZFDCQNOAWwo-zEA.png" /></figure><p>After updating the code you will get this error:</p><p><em>Referencing initializer ‘init(_:content:)’ on ‘ForEach’ requires that ‘RowGridDetails’ conform to ‘Identifiable’</em></p><p>To fix this error we need to confirm the Identifiable protocol to RowGridDetails struct. On confirming it you will be suggested to implement</p><pre>var id: ObjectIdentifier</pre><p><em>id</em> creates an instance that uniquely identifies the given class instance. This will be used by SwiftUI to identify which view to update/delete etc. <em>id</em> can be Int as well. If <em>id</em> is declared without the initialization then it will lead to passing an extra argument while initializing RowGridDetails instances. There are two ways to avoid this extra argument. First, initialize this at the time of declaration with some random integer value which will lead to having the same value for all the RowGridDetails hence uniqueness gets compromised. The other way suggests initializing it with UUID which fixes the first error and also uniqueness is maintained.</p><pre>var id = UUID()</pre><p>To fix the second error, we need to modify GridDetail but there we will not be asked to add <em>id</em> since its class type and class have unique ids attached to them.</p><pre><br>class GridDetail: Identifiable {<br>   var isSelected = false<br>   var player = 0<br>}</pre><p>After running the code, we will see the same results which we had till showing “Game ended”. Now let us start adding rules for finding the winner.</p><pre>private func isWinner(player: Int) -&gt; Bool {<br>   for row in gridDetails {<br>      if row.grids.filter({$0.player == player}).count == 3 {<br>         return true<br>      }<br>   }...</pre><p>A player number is passed as an argument for which we want to know the winning status. First, we are iterating through rows of checkerboard and filter player details for each grid. Since we have a 3*3 grid, return true if all three grids are selected by the same player.</p><pre>...<br>for index in 0..&lt;gridDetails.count {<br>   if gridDetails.filter({$0.grids[index].player == player}).count == 3 {<br>      return true<br>   }<br>}</pre><p>This is iterating through columns of the checkerboard, again returning true if the count is 3.</p><pre>if gridDetails[0].grids[0].player == player,<br>gridDetails[1].grids[1].player == player,<br>gridDetails[2].grids[2].player == player {<br>   return true<br>}</pre><pre>if gridDetails[0].grids[2].player == player,<br>gridDetails[1].grids[1].player == player,<br>gridDetails[2].grids[0].player == player {<br>   return true<br>}</pre><pre>return false</pre><p>It will check diagonally from top-left to bottom-right and if a winner is not found then diagonally from top-right to bottom-left. And at last, it will return false if none of the 4 conditions is satisfied. This is for one player, so we need to call it twice for both the players like this to decide a winner:</p><pre>func setWinner() {<br>   if isWinner(player: PlayerInfo.player1.rawValue) {<br>      winner = PlayerInfo.player1.rawValue<br>   }</pre><pre>   if isWinner(player: PlayerInfo.player2.rawValue) {<br>      winner = PlayerInfo.player2.rawValue<br>   }<br>}</pre><p>We will call this method inside the <em>onTapGesture</em> of MatrixBlock:</p><pre>settings.noOfStrikes += 1<br>settings.setWinner()<br>settings.setGameEnded()</pre><p>Our winner is decided but the game is not ended yet. To end the game once a winner is decided, just add a check for winner status inside the setGameEnded function:</p><pre>if winner != 0 || noOfStrikes == 9 {</pre><p>Won’t be a good idea to show who won the game? Let’s achieve it by modifying EndGameView.</p><pre>struct EndGameView: View {<br>   var winner: Int<br>   var body: some View {<br>      VStack {<br>         Text(“Game ended”)<br>         let message = winner == 0 ? “It’s a tie!!” : “Player \(winner) isa  winner”<br>         Text(“\(message)”)<br>            .foregroundColor(PlayerInfo.init(rawValue:   winner)?.getPlayerColor())<br>            .bold()<br>      }.multilineTextAlignment(.center)<br>       .font(.largeTitle)<br>   }<br>}</pre><p>Just run it and play the game. You will be able to see the winner details or the game tie info. Restrict the players to continue playing once a winner is decided, for that add the isGameEnded flag before performing any operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*--1CsDe2uMzPfxB6oNoRCw.gif" /></figure><p>Cheers to us!!! We have our own tic-tac-toe game that too fully functional.</p><p><strong>Do check out my other articles in this series:</strong></p><p><a href="https://medium.com/@roy11manisha/swiftui-text-view-styling-lets-play-tic-tac-toe-game-7987909584fb">Text view styling</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-tic-tac-toe-game-button-154a35997bc">Button</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-navigation-tic-tac-toe-game-d05d52cf4636">Navigation</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-shapes-tic-tac-toe-game-376073b11102">Shapes</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-drawing-tic-tac-toe-game-71fae0d46381">Drawing</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-list-tic-tac-toe-game-8ad7aaa4050">List</a></p><p><a href="https://medium.com/@roy11manisha/swiftui-animation-tic-tac-toe-game-4ffe37aba0b8">Animation</a></p><blockquote>If you liked this article then please appreciate it with claps and comments. This will encourage me to write more!!!!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bace4fbeb3ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/swiftui-data-flow-tic-tac-toe-game-bace4fbeb3ac">SwiftUI | Data flow | Tic-Tac-Toe Game</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>