<?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 Rajat Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rajat Kumar on Medium]]></description>
        <link>https://medium.com/@nsrajat?source=rss-ad600ed0399f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4Ece9CsQt9X8Xoiyw4o3vA.png</url>
            <title>Stories by Rajat Kumar on Medium</title>
            <link>https://medium.com/@nsrajat?source=rss-ad600ed0399f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:20:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nsrajat/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[How to detect scroll to bottom in SwiftUI]]></title>
            <link>https://medium.com/@nsrajat/how-to-detect-scrollview-scrolled-to-the-bottom-in-swiftui-87a7117be4cc?source=rss-ad600ed0399f------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a7117be4cc</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[scrollview]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 17:53:32 GMT</pubDate>
            <atom:updated>2024-06-21T08:27:11.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VH55SXEpU6tgWdXwsD-qrQ.jpeg" /></figure><p>I saw this post in one of the iOS developer slack channels asking about detection of scroll to bottom detection using SwiftUI. The original code was using UIScrollView warpped with UIViewRepresentable and then used UIHostingController to show SwiftUI views inside it. The solution worked but I felt like it was fighting the system. So, I decided to give it a go and implement it using SwiftUI.</p><p>In this article, we are going to explore how we can check if the scrollview has scrolled to the bottom of the content in iOS 16 with the help of Geometry Reader and Preference key.</p><blockquote>This is really easy to do in iOS 17 using <a href="https://developer.apple.com/documentation/swiftui/view/scrollposition(id:anchor:)"><strong>scrollposition</strong></a> modifier which accepts a binding which gives you identity of the view that is actively scrolled.</blockquote><p>This article requires you to know what Preference keys are, how to use them to get the offset of scrollview and Geometry readers. I’ll link to a few articles explaining that in the end. Let’s start!</p><p>The completed project can be found on my GitHub:</p><p><a href="https://github.com/rajatkj/ScrollViewWithScrolledToBottomDetection">GitHub - rajatkj/ScrollViewWithScrolledToBottomDetection: ScrollView scrolled to bottom detection in SwiftUI</a></p><p>We’re going to create a View with some content first so let’s go ahead and create our view.</p><pre>struct ScrollViewWithScrollToBottomDetectionView: View {<br>    <br>    var body: some View {<br>        ScrollView(.vertical, showsIndicators: false) {<br>            <br>            VStack(alignment: .leading, spacing: 0) {<br>                ForEach(0..&lt;100) { i in<br>                    Text(&quot;\(i + 1) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ei&quot;)<br>                        .foregroundStyle(.white)<br>                        .frame(height: 50)<br>                        .frame(maxWidth: .infinity)<br>                        .background(i.isMultiple(of: 2) ? .red : .mint)<br>                }<br>            }<br>        }<br>        .ignoresSafeArea()<br>    }<br>}<br><br>#Preview {<br>    ScrollViewWithScrollToBottomDetectionView()<br>}</pre><p>We’ve created a view which has a ScrollView with some dummy content repeated 100 times. I’ve applied an alternate background color to each element so we can see the separation clearly. I’ve also added ignoresSafeArea() to make scrollview expand the full screen, its not needed but I’ve added it just to make sure so that solution is evident in the demo.</p><h3>ScrollView Wrapper</h3><p>Now that out main view is ready, lets create another one which will act as a scrollview wrapper. Let’s call it <strong>EndDetectionScrollView </strong>and we’ll parameterize it to take our scroll content in and display it inside a scrollView.</p><pre>struct EndDetectionScrollView&lt;Content: View&gt;: View {<br>    <br>    let axis: Axis.Set<br>    let showsIndicators: Bool<br>    let content: () -&gt; Content<br>    <br>    init(axis: Axis.Set, showsIndicators: Bool, content: @escaping () -&gt; Content) {<br>        self.axis = axis<br>        self.showsIndicators = showsIndicators<br>        self.content = content<br>    }<br>    <br>    var body: some View {<br>        ScrollView(axis, showsIndicators: showsIndicators) {<br>            content()<br>        }<br>    }<br>}</pre><h3>Reading Offset</h3><p>First we’ll assign a coordinate space to the scrollView so we can observe the offset’s(<strong>maxY</strong>) value in that specific coordinate space. we can do that using coordinateSpace modifier.</p><pre>var body: some View {<br>        ScrollView(axis, showsIndicators: showsIndicators) {<br>            content()<br>        }<br>        .coordinateSpace(name: &quot;EndDetectionScrollView&quot;)<br>}</pre><p>We need to send the value of scroll offset of content() to the ancestor view so we can perform operations on it. We can do that using PreferenceKey, let’s create a struct that implements PreferenceKey protocol.</p><pre>struct OffsetPreferenceKey: PreferenceKey {<br>    static var defaultValue: CGFloat = .zero<br>    static func reduce(value: inout CGFloat, nextValue: () -&gt; CGFloat) {}<br>}</pre><p>Now that we’ve created a preference key, we’ll add a view to the top of the content in scrollview. This view will use a Geometry reader with a height 0, since we just need it to observe the maxY value. We will add a <strong>Color.clear </strong>inside the geometry reader and use it to set the value of preference to <strong>proxy.frame(in: .named(“EndDetectionScrollView”)).maxY.</strong></p><pre>var offsetReader: some View {<br>      GeometryReader { proxy in<br>          Color.clear<br>              .preference(<br>                  key: OffsetPreferenceKey.self,<br>                  value: proxy.frame(in: .named(&quot;EndDetectionScrollView&quot;)).maxY<br>              )<br>      }<br>      .frame(height: 0)<br>}</pre><pre>var body: some View {<br>      ScrollView(axis, showsIndicators: showsIndicators) {<br>          offsetReader<br>          content()<br>      }<br>      .coordinateSpace(name: &quot;EndDetectionScrollView&quot;)<br>}</pre><p>Now we can observe the value of preference key using the <strong>onPreferenceChange(_:perform:) </strong>modifier. The value set in the offsetReader view will be propagated to this method and we can use that value to perform operations. When you scroll down the offset value would be negative and when you scroll up the offset value would be positive.</p><pre>var body: some View {<br>    ScrollView(axis, showsIndicators: showsIndicators) {<br>        offsetReader<br>        content()<br>    }<br>    .coordinateSpace(name: &quot;EndDetectionScrollView&quot;)<br>    .onPreferenceChange(OffsetPreferenceKey.self) { offset in<br>        <br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*4kaD7RbtF6dax_ZI_6TxDA.gif" /><figcaption>Content offset overlay</figcaption></figure><p>Let’s take a look at how we can modify the value of the offset to be something useful in detect whether we’ve scrolled to bottom.</p><p>To do that we’d need two important values, the <strong>visibleContentHeight </strong>and <strong>totalContentHeight </strong>of the scrollView. Then we can subtract the visible height to total height and add the resulting value to offset. By doing that when we scroll to the end of scrollview, that resulting value will reach 0 or negative(since the scrollView bounces).</p><pre>(totalContentHeight - visibleContentHeight) + offset &lt;= 0<br>// true: Scrolled to bottom<br>// false: Not scrolled to bottom</pre><h4>How do we get the visibleContentHeight<strong> </strong>and <strong>totalContentHeight</strong>?</h4><p>Well we can use the Geometry Reader again to do this. To get the total height of the content we’ll add a geometry reader as an overlay to the content passed to our wrapper which will give us the total height of the content inside scrollView.</p><p>First let’s add two properties to the EndDetectionScrollView.</p><pre>@State private var visibleContentHeight: CGFloat = 0<br>@State private var totalContentHeight: CGFloat = 0</pre><pre>var body: some View {<br>  ScrollView(axis, showsIndicators: showsIndicators) {<br>      offsetReader<br>      content()<br>          .overlay {<br>              GeometryReader { geometry in<br>                  Color.clear.onAppear {<br>                      self.totalContentHeight = geometry.frame(in: .local).height<br>                  }<br>              }<br>          }<br>  }<br>  .coordinateSpace(name: &quot;EndDetectionScrollView&quot;)<br>  .onPreferenceChange(OffsetPreferenceKey.self) { offset in<br><br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*k0DvmeBdUfcdAhBdsCZpIg.png" /><figcaption>Total Content Height</figcaption></figure><p>Next we would need the visible height of the scrollView. For that we can simply repeat the process but this time add the overlay to the <strong>ScrollView </strong>instead.</p><pre>ScrollView(axis, showsIndicators: showsIndicators) {<br>    offsetReader<br>    content()<br>        .overlay {<br>            GeometryReader { geometry in<br>                Color.clear.onAppear {<br>                    self.totalContentHeight = geometry.frame(in: .local).height<br>                }<br>            }<br>        }<br>}<br>.overlay {<br>    GeometryReader { geometry in<br>        Color.clear.onAppear {<br>            self.visibleContentHeight = geometry.frame(in: .local).height<br>        }<br>    }<br>}<br>.coordinateSpace(name: &quot;EndDetectionScrollView&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*5Wh9gdyv4C_4lNNnsMlGjQ.png" /><figcaption>Visible Content Height</figcaption></figure><p>We have all the values we need to detect whether the scrollview has scrolled to the bottom.</p><p>Let’s add the calculation to our onPreferenceChange modifier and see what it tells us. We’ll also add a @State var to hold the boolean value of whether we’ve scrolled to end.</p><pre>@State var hasScrolledToEnd: Bool</pre><pre>ScrollView(axis, showsIndicators: showsIndicators) {<br>    offsetReader<br>    content()<br>        .overlay {<br>            GeometryReader { geometry in<br>                Color.clear.onAppear {<br>                    self.totalContentHeight = geometry.frame(in: .local).height<br>                }<br>            }<br>        }<br>}<br>.overlay {<br>    GeometryReader { geometry in<br>        Color.clear.onAppear {<br>            self.visibleContentHeight = geometry.frame(in: .local).height<br>        }<br>    }<br>}<br>.coordinateSpace(name: &quot;EndDetectionScrollView&quot;)<br>.onPreferenceChange(OffsetPreferenceKey.self) { offset in<br>    hasScrolledToBottom = (totalContentHeight - visibleContentHeight) + offset &lt;= 0<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*6PhnS8CcVkjHYC6xiXfI1A.gif" /><figcaption>Partial</figcaption></figure><p>You see in the video above the it initially shows that you’ve scrolled to the end. It isn’t until we scroll that we get values of total and visible height. Also, when the scrollview’s content doesn’t overflow we need to add a condition to check if <strong>totalContentHeight</strong> is smaller than the <strong>visibleContentHeight </strong>in which case the value should always return false.</p><blockquote>I haven’t had a chance to look into why the initial values of total and visible heights are 0 as the onAppear should be called and should set the values of heights. if anyone has any idea, please let me know.</blockquote><p>To avoid this issue with initial value we can simply add the condition to check if totalContentHeight and visibleContentHeight are not equal to zero. Once the scrolling starts we’ll get those values and it will work correctly.</p><pre>if totalContentHeight &lt; visibleContentHeight {<br>    hasScrolledToEnd = false<br>    return<br>}<br>if totalContentHeight != 0 &amp;&amp; visibleContentHeight != 0 {<br>     hasScrolledToBottom = (totalContentHeight - visibleContentHeight) + offset &lt;= 0<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*xgQeOb8-pPfxdprfJu-TjQ.gif" /><figcaption>Full</figcaption></figure><p>And there we have it!</p><h3>One more thing</h3><p>We can make the <strong>hasScrolledToEnd </strong>a @Binding so we can observe that in our main view. Here’s the finished code.</p><pre>struct EndDetectionScrollView&lt;Content: View&gt;: View {<br>    let axis: Axis.Set<br>    let showIndicators: Bool<br>    @Binding var hasScrolledToEnd: Bool<br>    let content: () -&gt; Content<br>    <br>    @State private var visibleContentHeight: CGFloat = 0<br>    @State private var totalContentHeight: CGFloat = 0<br>    <br>    init(_ axis: Axis.Set,<br>         showIndicators: Bool,<br>         hasScrolledToEnd: Binding&lt;Bool&gt;,<br>         @ViewBuilder content: @escaping () -&gt; Content) {<br>        self.content = content<br>        self.axis = axis<br>        self.showIndicators = showIndicators<br>        self._hasScrolledToEnd = hasScrolledToEnd<br>    }<br>    <br>    var body: some View {<br>        ScrollView(axis, showsIndicators: showIndicators) {<br>            offsetReader<br>            content()<br>                .overlay(content:  {<br>                    GeometryReader(content: { geometry in<br>                        Color.clear.onAppear {<br>                            self.totalContentHeight = geometry.frame(in: .global).height<br>                        }<br>                    })<br>                })<br>                <br>        }<br>        .overlay(content:  {<br>            GeometryReader(content: { geometry in<br>                Color.clear.onAppear {<br>                    self.visibleContentHeight = geometry.frame(in: .global).height<br>                }<br>            })<br>        })<br>        .coordinateSpace(name: &quot;frameLayer&quot;)<br>        .onPreferenceChange(OffsetPreferenceKey.self, perform: { offset in<br>            if totalContentHeight &lt; visibleContentHeight {<br>                hasScrolledToEnd = false<br>                return<br>            }<br>            print(&quot;Total \(totalContentHeight) visible: \(visibleContentHeight)&quot;)<br>            if totalContentHeight != 0 &amp;&amp; visibleContentHeight != 0 {<br>                if (totalContentHeight - visibleContentHeight) + offset &lt;= 0 {<br>                    hasScrolledToEnd = true<br>                } else {<br>                    hasScrolledToEnd = false<br>                }<br>            } else {<br>                hasScrolledToEnd = false<br>            }<br>        })<br>    }<br>    <br>    var offsetReader: some View {<br>        GeometryReader { proxy in<br>            Color.clear<br>                .preference(<br>                    key: OffsetPreferenceKey.self,<br>                    value: proxy.frame(in: .named(&quot;frameLayer&quot;)).maxY<br>                )<br>        }<br>        .frame(height: 0)<br>    }<br>}</pre><pre>struct ScrollViewWithScrollToBottomDetectionView: View {<br>    <br>    @State var hasScrolledToEnd: Bool = false<br>    <br>    var body: some View {<br>        EndDetectionScrollView(.vertical, showIndicators: false, hasScrolledToEnd: $hasScrolledToEnd) {<br>            <br>            VStack(alignment: .leading, spacing: 0) {<br>                ForEach(0..&lt;100) { i in<br>                    Text(&quot;\(i + 1) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ei&quot;)<br>                        .foregroundStyle(.white)<br>                        .frame(height: 50)<br>                        .frame(maxWidth: .infinity)<br>                        .background(i.isMultiple(of: 2) ? .cyan : .mint)<br>                }<br>            }<br>        }<br>        .overlay(alignment: .bottom) {<br>            overlayView<br>        }<br>        .ignoresSafeArea()<br>    }<br>    <br>    @ViewBuilder<br>    private var overlayView: some View {<br>        ZStack {<br>            Color.clear<br>                .background(.ultraThinMaterial)<br>                .ignoresSafeArea()<br>            Text(&quot;You have \(hasScrolledToEnd ? &quot;&quot; : &quot;not &quot;)scrolled to bottom&quot;)<br>                .foregroundStyle(.black)<br>                .bold()<br>                .font(.title3)<br>        }<br>        .frame(height: 100)<br>        .animation(.easeInOut, value: hasScrolledToEnd)<br>    }<br>}<br><br>#Preview {<br>    ScrollViewWithScrollToBottomDetectionView()<br>}</pre><h3>Conclusion</h3><p>Personally I don’t like this solution and would rather prefer the iOS 17 api’s but we all know we need to support the iOS versions earlier than that at least for another one or two years.</p><p>Also, there are endless possibilities when it comes to observing the offset, it lets you do all sort of things like implementing a sticky header which I’ll be looking into next along with other cool things.</p><h4>References</h4><ul><li><a href="https://developer.apple.com/documentation/swiftui/geometryreader">GeometryReader | Apple Developer Documentation</a></li><li><a href="https://www.swiftbysundell.com/articles/observing-swiftui-scrollview-content-offset/">Observing the content offset of a SwiftUI ScrollView | Swift by Sundell</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a7117be4cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding String.Index in Swift]]></title>
            <link>https://medium.com/@nsrajat/understanding-string-index-in-swift-a8c8a5229204?source=rss-ad600ed0399f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c8a5229204</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 16:57:43 GMT</pubDate>
            <atom:updated>2023-10-10T16:57:43.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VH55SXEpU6tgWdXwsD-qrQ.jpeg" /></figure><p>So, a few weeks back I started solving Leetcode problems and found myself enjoying the challenge, however, I struggled to navigate String indices and comparing characters between different strings.</p><p>Also, The top solutions were often in other languages — a minor inconvenience except for String problems. Anyway, to sidestep potential demotivation, I took a pragmatic shortcut — converting Strings to Arrays for easier iteration and comparison.</p><pre>let string = &quot;Hello world!&quot;<br>let array = Array(string)<br>// Output: [&quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;, &quot; &quot;, &quot;w&quot;, &quot;o&quot;, &quot;r&quot;, &quot;l&quot;, &quot;d&quot;, &quot;!&quot;]</pre><p>It didn’t feel right! So, I went on a mission to understand String indices in order to eliminate the need for unnecessary memory allocation.</p><p>In this article, I’ll be sharing what I learned about navigating and comparing <strong>Strings</strong> using <strong>String.Index</strong>. Let’s get started!</p><h3>Strings in Swift</h3><p>String in Swift is a <strong><em>@frozen struct </em></strong>that is defined in the official documentation as:</p><blockquote>A Unicode string value that is a collection of characters.</blockquote><p>In Swift, a <strong>String</strong> is a sequence of characters that represents textual data. It is one of the fundamental data types provided by the language for working with text. Strings in Swift are Unicode correct, locale insensitive allowing them to be used as keys in a Dictionary and for other purposes.</p><p>You can create a String using string literals</p><pre>let message = &quot;Hello world!&quot;</pre><p>or using String interpolations. String interpolation is a feature in Swift that allows you to include constants, variables, literals, and expressions within string literals. It provides a readable way to construct strings by embedding values directly into the string.</p><p>In Swift, string interpolation is performed by placing the value within a set of parentheses and prefixed with a backslash \ within a string literal. Here&#39;s a simple example:</p><pre>let name = &quot;Rajat&quot;<br>let age = 29<br>let message = &quot;Hello, my name is \(name) and I am \(age) years old.&quot;<br>//Output: Hello, my name is Rajat and I am 29 years old.</pre><p>You can also create a multiline string literals in swift if you enclose them in three double quotation marks, like this:</p><pre>let message = &quot;&quot;&quot;<br> ____      _       _   _  _____<br>|  _ \    / \     | | / \|_   _|<br>| |_) |  / _ \ _  | |/ _ \ | |<br>|  _ &lt;  / ___ \ |_| / ___ \| |<br>|_| \_\/_/   \_\___/_/   \_\_|<br>&quot;&quot;&quot;</pre><h3>Why can’t we use Int indexes to get a character in String?</h3><p>In Swift, the <strong>RandomAccessCollection</strong> protocol is designed for collections that can provide direct access to elements at any index in constant time. While arrays in Swift conform to <strong>RandomAccessCollection</strong> because they provide efficient random access, String is not a <strong>RandomAccessCollection</strong> for a specific reason: the nature of Unicode and the complexity of accessing characters by index.</p><p>Strings in Swift are Unicode correct, and Unicode characters can have variable widths. Some characters require more than one UTF-16 code unit to represent. Unlike some other programming languages where strings are represented as arrays of bytes, in Swift, strings are designed to handle complex international characters, which can have varying byte sizes.</p><p>For example the emoji “🎸” is represented by more than one UTF-16 code unit. If you were to access it using an integer subscript, it might only give you part of the character or lead to incorrect results.</p><pre>let message = &quot;🎸&quot;<br>print(Array(message.utf16))<br>//Output: [55356, 57272]</pre><p>So what do we do?</p><h3>String.Index</h3><p><strong>String.Index</strong> is a type that represents the position of a character or code unit in a string. It is used for indexing and navigating through the characters of a string. Unlike an integer index, which might be used in other programming languages, <strong>String.Index</strong> is more versatile. Let’s go ahead and explore some basic usage of <strong>String.Index</strong>.</p><h4>startIndex</h4><p>To access the first character we can use the <strong>startIndex</strong> property of a String. it gives us the position of the first character in a nonempty string.</p><pre>let message = &quot;Hello World!&quot;<br>// message.startIndex<br>print(message[message.startIndex])<br>// Output: H</pre><h4>endIndex</h4><p>We’ve barely dipped our toes in, and things are already getting a bit tricky. You see, the <strong>endIndex</strong> property gives us the index right after the last character and if we try to access a character at <strong>endIndex</strong> the index will be out of bounds.</p><pre>let message = &quot;Hello World!&quot;<br>//message.endIndex<br>print(message[message.endIndex])<br>// Output: Fatal error: String index is out of bounds</pre><p>So, how do we get the last character in a String? We can use the method <strong>index(before: ) </strong>and pass the endIndex to get the last character in a String.</p><pre>let message = &quot;Hello World!&quot;<br>print(message[message.index(before: message.endIndex)])<br>// Output: !</pre><h4>index(_:offsetBy:)</h4><p>Alright, we have first and last character but how do we access a character at a specific location e.g. second character, third last character. We can use the method <strong>index(_:offsetBy:) </strong>to do that. The <strong><em>offsetBy</em></strong> value expects an Int type so it can be positive or negative and starts from the given index.</p><pre>let message = &quot;Hello World!&quot;<br>let startIndex = message.startIndex<br>let indexOfSecondCharacter = message.index(startIndex, offsetBy: 1)<br>print(message[indexOfSecondCharacter])<br>// Output: e<br><br>let endIndex = message.endIndex<br>let indexOfThirdLastCharacter = message.index(endIndex, offsetBy: -3)<br>print(message[indexOfThirdLastCharacter])<br>// Output: l</pre><p>Remember that the <strong>endIndex</strong> gives you the index <strong>after</strong> the last character, so you have to decrement offset by one.</p><h4>index(before:)</h4><p>We’ve already seen this method in action in the <strong>endIndex</strong> example, it returns the position immediately before the index passed in the parameter. If we pass <strong>startIndex </strong>into it would result in <strong>Fatal error: String index is out of bounds.</strong></p><pre>let message = &quot;Hello World!&quot;<br>print(message[message.index(before: message.endIndex)])<br>// Output: !</pre><h4>index(after:)</h4><p>Similar to <strong>before</strong>, this method returns the index immediately after the index passed in the parameter.</p><pre>let message = &quot;Hello World!&quot;<br>print(message[message.index(after: message.startIndex)])<br>// Output: e</pre><h4>Iterating through a String</h4><p>We can use a <strong>for-in</strong> loop with <strong>indices</strong> property to iterate through a string.</p><pre>let message = &quot;Hello World!&quot;<br><br>for index in message.indices {<br>    print(message[index], terminator: &quot; &quot;)<br>}<br><br>// Output: H e l l o   W o r l d ! </pre><p><em>Note: I’ve used a whitespace terminator so that it doesn’t print each character in a new line.</em></p><h4>Using Ranges</h4><p>We’ve had a look at how we can access one character of a string, now let’s see how we can create ranges using <strong>String.Index</strong> and extract <strong>substrings</strong> from a string.</p><p>I’m not gonna go in details of range operators, you can find more about them <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators/">here</a>.</p><p>You can use the range to get the first 5 characters of a string by creating a range from <strong>startIndex </strong>to <strong>index(startIndex, offsetBy: 5)</strong>. it’ll look something like this:</p><pre>let message = &quot;Hello World!&quot;<br><br>let firstFiveRange = message.startIndex..&lt;message.index(message.startIndex, offsetBy: 5)<br>let firstFiveCharacters = message[firstFiveRange]<br>print(firstFiveCharacters)<br>// Output: Hello</pre><p>Or get the last 5 characters by creating a range using <strong>endIndex</strong></p><pre>let message = &quot;Hello World!&quot;<br>let lastFiveRange = message.index(message.endIndex, offsetBy: -5)..&lt;message.endIndex<br>let lastFiveCharacters = message[lastFiveRange]<br>print(lastFiveCharacters)<br>// Output: orld!</pre><h4>range(of:)</h4><p>Talking about ranges what if you needed to find the range of a given substring inside the string, we can use <strong>range(of:) </strong>method on a string and pass the substring as a parameter. It will return <em>nil</em> if the substring doesn’t exist.</p><pre>let message = &quot;Hello World!&quot;<br>let substring = &quot;ello&quot;<br><br>if let firstIndexOfSubstring = message.range(of: substring)?.lowerBound {<br>    print(message[firstIndexOfSubstring])<br>}<br><br>// Output: e</pre><p>Also, since the <strong>lowebound </strong>is of <strong>String.Index </strong>type if you want to know the Int value of the index you can use <strong>distance(from:to:) </strong>method on the index to get the value.</p><pre>let message = &quot;Hello World!&quot;<br>let substring = &quot;ello&quot;<br><br>if let lastIndexOfSubstring = message.range(of: substring)?.upperBound {<br>    let intValue = message.distance(from: message.startIndex, to: lastIndexOfSubstring)<br>    print(intValue)<br>}<br><br>// Output: 5(index of letter o in message)</pre><h4>Comparison</h4><p>When we subscript a string the result with an Index, the result that we get is of <a href="https://developer.apple.com/documentation/swift/character">Character</a> type which not only lets us compare the results easily using comparison operators.</p><pre>let message = &quot;ab&quot;<br><br>let firstIndex = message.startIndex<br>let secondIndex = message.index(message.startIndex, offsetBy: 1)<br><br>print(message[firstIndex] &lt; message[secondIndex])<br>// Output: true</pre><p>Also, if you look into the <a href="https://developer.apple.com/documentation/swift/character">documentation</a> there are several helper methods to inspect or to check the case. I’m not going to list them all but here’s an example.</p><pre>let message = &quot;ab&quot;<br>let character = message[message.startIndex]<br><br>character.isASCII<br>character.isCased<br>character.isNumber<br>character.isUppercase<br>character.isWhitespace</pre><h3>Conclusion</h3><p>And that wraps up the fundamentals of <strong>String.Index</strong>! I hope this gave you a good understanding of how to use Indices to efficiently access, iterate, compare and manipulate Strings. While it does take some focused practice to get comfortable with String indices, I do think it is a worthwhile investment.</p><p>Hope you enjoyed this article, Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c8a5229204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallax effect — SwiftUI]]></title>
            <link>https://medium.com/@nsrajat/parallax-effect-swiftui-82fd3b172aa0?source=rss-ad600ed0399f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82fd3b172aa0</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 17:35:55 GMT</pubDate>
            <atom:updated>2023-10-06T17:35:55.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parallax effect — SwiftUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHCSZ-AlFlT5XhvmB8Zswg.jpeg" /></figure><p>Back in 2015, when I got my first job as an iOS developer, I was poking around on iPhone, something caught my eye: the home screen background moving ever so slightly when I tilted the phone. It had me totally hooked! So, naturally, I thought, Let’s add that to the app I was working on. I did manage to implement it back then using Objective-C.</p><p>In this article, I’m gonna walk through on how you can do the same using <strong>SwiftUI</strong> and CoreMotion. Let’s dive in!</p><h3>What is parallax?</h3><p>A quick google for the meaning of word parallax says,</p><blockquote>the effect whereby the position or direction of an object appears to differ when viewed from different positions</blockquote><p>To achieve parallax effect we need to know when the device is tilted in either direction so we can move a view/image, which is where CoreMotion comes in to play. First, let’s understand the information we need from the framework.</p><h3>Pitch, Yaw and Roll</h3><p>Generally used in the dynamics of flying vehicles these terms can seem a bit confusing so let’s begin with explaining them first:</p><p><strong>Pitch: </strong>refers to the rotation of an object about its lateral axis. Imagine a line running from wingtip to wingtip on an aircraft. Pitching is like nodding your head in affirmation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FmGu2b0snP1znFGjDKQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FmGu2b0snP1znFGjDKQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FmGu2b0snP1znFGjDKQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="667" frameborder="0" scrolling="no"><a href="https://medium.com/media/e12041b081e45dc43ece9455c3f9c799/href">https://medium.com/media/e12041b081e45dc43ece9455c3f9c799/href</a></iframe><p><strong>Yaw: </strong>refers to the rotation of an object about its vertical axis. Using the aircraft example again, yawing is like turning your head from side to side.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAaMkkZprRejxVImxqd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FAaMkkZprRejxVImxqd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FAaMkkZprRejxVImxqd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="598" frameborder="0" scrolling="no"><a href="https://medium.com/media/0937f03101e0325b9fb8ededd2d5b019/href">https://medium.com/media/0937f03101e0325b9fb8ededd2d5b019/href</a></iframe><p><strong>Roll: </strong>refers to<strong> </strong>the rotation of an object about its longitudinal axis. This is like tilting your head from one side to another.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FFE8UDL4pOI6CQmt4QF%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FFE8UDL4pOI6CQmt4QF%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FFE8UDL4pOI6CQmt4QF%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="717" frameborder="0" scrolling="no"><a href="https://medium.com/media/8095edc306f0212fe9d09304b9882339/href">https://medium.com/media/8095edc306f0212fe9d09304b9882339/href</a></iframe><h3><strong>CoreMotion</strong></h3><p>As explained above, to achieve the Parallax effect we only need the pitch and the roll values.</p><p>Go ahead and create a project in swiftUI and add a Swift file named <strong>MotionManager.swift</strong>.</p><p>With CoreMotion framework we can get these values by subscribing to the device motion updates. We’re going to first create a MotionManager class and make it confirm to <strong>ObservableObject</strong> so we can add <strong>@Published</strong> properties and use it in SwiftUI view to observe the changes.</p><pre>import CoreMotion<br><br>class MotionManager: ObservableObject</pre><p>Next we’re going to add an instance of <strong>CMMotionManager</strong> to the class which will help us to subscribe to device motion updates</p><pre>private let motionManager = CMMotionManager()</pre><p>then, we’re going to add a method to the class which is going to check if <strong><em>isDeviceMotionAvailable </em></strong>property of motionManager is true and set the <strong><em>deviceMotionUpdateInterval </em></strong>to a value of 0.01 so we can get frequent updates resulting in smoother animation.</p><pre>func startMonitoringMotionUpdates() {<br>        <br>        guard self.motionManager.isDeviceMotionAvailable else {<br>            print(&quot;Device motion not available&quot;)<br>            return<br>        }<br>        <br>        self.motionManager.deviceMotionUpdateInterval = 0.01<br>}</pre><p>then we’re going to use the method <strong><em>func startDeviceMotionUpdates(to queue: OperationQueue, withHandler handler: @escaping CMDeviceMotionHandler) </em></strong>to subscribe to the motion updates. Our start monitoring method will look something like this.</p><pre>func startMonitoringMotionUpdates() {<br>        <br>        guard self.motionManager.isDeviceMotionAvailable else {<br>            print(&quot;Device motion not available&quot;)<br>            return<br>        }<br>        <br>        self.motionManager.deviceMotionUpdateInterval = 0.01<br>        <br>        self.motionManager.startDeviceMotionUpdates(to: .main) { motion, error in<br>            <br>        }<br> }</pre><p>Now, let’s add two published properties to this class to save the pitch and roll values that we get from motion manager and set them in the closure provided by <strong><em>startDeviceMotionUpdates. </em></strong>The motion manager class looks something like this.</p><pre>class MotionManager: ObservableObject {<br>    <br>    private let motionManager = CMMotionManager()<br><br>    @Published var pitch: Double = 0.0<br>    @Published var roll: Double = 0.0<br>    <br>    func startMonitoringMotionUpdates() {<br>        <br>        guard self.motionManager.isDeviceMotionAvailable else {<br>            print(&quot;Device motion not available&quot;)<br>            return<br>        }<br>        <br>        self.motionManager.deviceMotionUpdateInterval = 0.01<br>        <br>        self.motionManager.startDeviceMotionUpdates(to: .main) { motion, error in<br>            guard let motion = motion else { return }<br>            self.pitch = motion.attitude.pitch<br>            self.roll = motion.attitude.roll<br>        }<br>    }<br>    <br>    func stopMonitoringMotionUpdates() {<br>        self.motionManager.stopDeviceMotionUpdates()<br>    }<br>}</pre><p>Notice I’ve added the <strong><em>stopMonitoringMotionUpdates </em></strong>method so we can stop the updates if we’re going out of the screen.</p><p>With our motion manager ready we can now go on to add this to a view to see the effect in action.</p><h3><strong>SwiftUI</strong></h3><p>We’re going to use the pitch and roll values from motion manager to offset <strong>x</strong> and <strong>y</strong> of a view(in this case an image) so that it moves when we tilt the device.</p><p>In the <strong>ContentView.swift</strong>, we’re going to add the <strong>@ObservedObject</strong> property of class <strong>MotionManager</strong> that we just created which will give access to the published pitch and roll variables.</p><pre>    @ObservedObject var motionManager = MotionManager()</pre><p>Next, we’re going to start monitoring updates by calling the <strong><em>startMonitoringMotionUpdates </em></strong>method of the MotionManager in <strong>onAppear </strong>of our view.</p><pre>   var body: some View {<br>        <br>        Text(&quot;Hello World!&quot;)<br>            .onAppear {<br>                motionManager.startMonitoringMotionUpdates()<br>            }<br>    }</pre><p>Let’s add an image in place of the text.</p><pre>var body: some View {<br>        Image(&quot;image&quot;)<br>            .onAppear {<br>                motionManager.startMonitoringMotionUpdates()<br>            }<br>}</pre><p>If you run the app on a device and put a breakpoint in the motion manager, you’d be able to see that we’re getting pitch and roll values when we tilt the device. Let’s use these values to change the offset of the Image. We’re gonna update the <strong>x</strong> offset with <strong>roll</strong> because we want to move the image horizontally and <strong>y</strong> with <strong>pitch</strong>.</p><pre>var body: some View {<br>        <br>        Image(&quot;image&quot;)<br>            .offset(x: motionManager.roll, y: motionManager.pitch)<br>            .onAppear {<br>                motionManager.startMonitoringMotionUpdates()<br>            }<br>    }</pre><p>After adding that one line of code, we run the app and voila!! we have the parallax effect.</p><p>But wait, you don’t see anything moving, well that’s because the values we get from motion manager look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*hUQIQSYpXNk0G81ShnbWoQ.png" /></figure><p>These values are too small to notice anything, let’s go ahead and multiply the values by 100.</p><pre>var body: some View {<br>        Image(&quot;image&quot;)<br>            .offset(x: motionManager.roll * 100, y: motionManager.pitch * 100)<br>            .onAppear {<br>                motionManager.startMonitoringMotionUpdates()<br>            }<br>}</pre><p>And now when you run it and tilt the device, it’ll look like this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FtWOK75TB5wM6gz143h%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdzd1OGwyM3ViZm1teGh3enp4NDR5YnV5a3ZzZnBuMDdlN2h3bGkxdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FtWOK75TB5wM6gz143h%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FtWOK75TB5wM6gz143h%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="759" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ac15c468fc4c603c7ec5ebe8559cb90/href">https://medium.com/media/9ac15c468fc4c603c7ec5ebe8559cb90/href</a></iframe><p>That’s the essence of it — simple yet truly wonderful!</p><p><a href="https://github.com/rajatkj/ImageParallax">GitHub - rajatkj/ImageParallax: Parallax effect on image in SwiftUI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82fd3b172aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>