<?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 Ryan Jennings on Medium]]></title>
        <description><![CDATA[Stories by Ryan Jennings on Medium]]></description>
        <link>https://medium.com/@ryanjennings_82367?source=rss-29096ae0f03d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GF_7NXiJ4AC5RTup</url>
            <title>Stories by Ryan Jennings on Medium</title>
            <link>https://medium.com/@ryanjennings_82367?source=rss-29096ae0f03d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:47:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryanjennings_82367/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[SwiftUI Pro Tips: PreferenceKey]]></title>
            <link>https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-preferencekey-360505ff8fbb?source=rss-29096ae0f03d------2</link>
            <guid isPermaLink="false">https://medium.com/p/360505ff8fbb</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ryan Jennings]]></dc:creator>
            <pubDate>Tue, 10 May 2022 19:39:02 GMT</pubDate>
            <atom:updated>2022-05-17T16:18:12.706Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is part of a series on SwiftUI pro tips. To read the last article in the series, <a href="https://medium.com/ancestry-engineering/swiftui-pro-tips-4-6-4139efd1d087">click here</a>.</blockquote><p>SwiftUI makes it easy to develop beautiful layouts with zero complications (no nasty unsatisfiable constraint warnings to worry about). There is no need for you to know the inner workings of the layout system, or be concerned with the end positioning or sizing of your views. Things just work. But what if you <strong><em>do</em></strong> want sizing and positioning information? What if, for instance, you wanted to overlay your views with additional information or maybe a tutorial that explains how to use a particular button and presents a callout that directly points to that button? You’d need to know the exact location of that button onscreen. Today’s set of tips will explain exactly how to do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnlSaezscKXSThPqR4fwPA.png" /><figcaption>“<a href="https://sketchfab.com/3d-models/old-key-69e71d81492548de88edb7f81065d80c">Old key</a>” by <a href="https://sketchfab.com/krolzuzannapl">SusanKing</a> is licensed under <a href="https://creativecommons.org/licenses/by/2.0/">CC BY 2.0</a></figcaption></figure><h4><strong>Pro tip #7: Advanced sizing using PreferenceKey</strong></h4><p>As you may or may not know, you can use GeometryReader to get the relative size of containers like this:</p><pre>public var body: some View {<br>  GeometryReader { geometry in<br>    HStack(spacing: 0) {<br>      Text(&quot;Left&quot;)<br>        .frame(width: geometry.size.width * 0.33)<br>      Text(&quot;Right&quot;)<br>        .frame(width: geometry.size.width * 0.67)<br>    }<br>  }<br>  .frame(height: 50)<br>}</pre><p>The above GeometryReader will return the rendered width of the container (the height is hardcoded via the frame). Knowing the width of the GeometryReader, you can then set the inner Text views width to some fraction of the full width.</p><p>But GeometryReader will always only return its own width and height. And a GeometryReader takes up as much space as it can. The reason for the .frame(height: 50) above is because, without it, that GeometryReader would fill the entire height of the body, and would return that entire height if geometry.size.height was referenced.</p><p>Let’s say you want the exact width and height of a Text view. Using a GeometryReader will not work because it will only return its own size. Let’s also say that text was centered within its container, and just a short bit of text, like “Hello world”. How do we accurately get the width and height of that Text view?PreferenceKey comes to our rescue! But its implementation is a bit more involved than a simple geometry reader.</p><p>First, create a custom PreferenceKey that will be used to reference the size of the container:</p><pre>struct ViewSizeKey: PreferenceKey {<br>  static var defaultValue: CGSize = .zero<br>  static func reduce(value: inout CGSize, nextValue: () -&gt; CGSize) {<br>    value = nextValue()<br>  }<br>}</pre><p>Next, create a view which will calculate its size and assign it to the ViewSizeKey:</p><pre>struct ViewGeometry: View {<br>  var body: some View {<br>    GeometryReader { geometry in<br>      Color.clear<br>        .preference(key: ViewSizeKey.self, value: geometry.size)<br>    }<br>  }<br>}</pre><p>You can now easily use ViewGeometry to get a view’s width and height like this:</p><pre>VStack(alignment: .center) {<br>   Text(&quot;Hello world&quot;)<br>      .background(ViewGeometry())<br>      .onPreferenceChange(ViewSizeKey.self) { size in<br>         print(&quot;Text width:&quot;, size.width)<br>         print(&quot;Text height:&quot;, size.height)<br>      }<br>}</pre><p>This will accurately print the exact width and height of “Hello world”.</p><p>Special thanks to pawello2222 Stack Overflow answer here <a href="https://stackoverflow.com/a/64452757/215845">https://stackoverflow.com/a/64452757/215845</a> for originally solving this problem for me!</p><h4><strong>Pro tip #8: Getting view anchors using PreferenceKey</strong></h4><p>You can also get the origin of a container using a different PreferenceKey. The origin is the top, left coordinate of a container. Unlike size, to obtain this value, you do need a GeometryReader.</p><p>A GeometryReader returns a GeometryProxy. This proxy can be used to get the size of the GeometryReader. It also contains all of the anchors of the subviews of the GeometryReader. One relevant anchor is the origin.</p><p>First, create a custom PreferenceKey that will be used to reference an anchor of the container.</p><pre>struct ViewAnchorKey: PreferenceKey {<br>  static let defaultValue = ViewAnchorData()<br>  static func reduce(value: inout ViewAnchorData, nextValue: () -&gt; ViewAnchorData) {<br>    value.anchor = nextValue().anchor ?? value.anchor<br>  }<br>}</pre><pre>struct ViewAnchorData: Equatable {<br>  var anchor: Anchor&lt;CGRect&gt;? = nil<br>  static func == (lhs: ViewAnchorData, rhs: ViewAnchorData) -&gt; Bool {<br>    return false<br>  }<br>}</pre><p>Next, create a view which will calculate the anchor and assign it to the ViewAnchorKey. You can actually add this new key to the ViewGeometry created earlier:</p><pre>struct ViewGeometry: View {<br>  var body: some View {<br>    GeometryReader { geometry in<br>      Color.clear<br>        .preference(key: ViewSizeKey.self, value: geometry.size)<br>        .anchorPreference(key: ViewAnchorKey.self, value: .bounds) {<br>          ViewAnchorData(anchor: $0)<br>        }<br>    }<br>  }<br>}</pre><p>You can now use ViewGeometry to access a container’s origin like this:</p><pre>struct ContentView: View {<br>  var body: some View {<br>    GeometryReader { geo in<br>      VStack(alignment: .center, spacing: 0) {<br>        Rectangle()<br>          .foregroundColor(.black)<br>          .frame(height: 200)<br>        Text(&quot;Hello&quot;)<br>          .background(ViewGeometry())<br>          .onPreferenceChange(ViewAnchorKey.self) { data in<br>            guard let anchor = data.anchor else { return }<br>            print(&quot;Text 1 origin:&quot;, geo[anchor].origin)<br>          }<br>          .onPreferenceChange(ViewSizeKey.self) { size in<br>            print(&quot;Text 1 size:&quot;, size)<br>          }<br>        Text(&quot;World&quot;)<br>          .background(ViewGeometry())<br>          .onPreferenceChange(ViewAnchorKey.self) { data in<br>            guard let anchor = data.anchor else { return }<br>            print(&quot;Text 2 origin:&quot;, geo[anchor].origin)<br>          }<br>          .onPreferenceChange(ViewSizeKey.self) { size in<br>            print(&quot;Text 2 size:&quot;, size)<br>          }<br>      }<br>    }<br>  }<br>}</pre><p>And that will print out something like:</p><pre>Text 1 size: (39.0, 20.333333333333332)<br>Text 1 origin: (175.66666666666666, 200.0)<br>Text 2 size: (45.0, 20.333333333333332)<br>Text 2 origin: (172.66666666666666, 220.33333333333331)</pre><p>Keep in mind that the anchors are relative to the GeometryReader. So if you’re interested in screen coordinates, ContentView (above) needs to be fullscreen and the GeometryReader needs to include the entire subview hierarchy, not be nested within a subview.</p><h4>More about PreferenceKey</h4><p>When you do a Google search for PreferenceKey, one of the first things you’ll read about is Apple’s own use case, which is to allow you to set a navigation title from anywhere in your SwiftUI code.</p><pre><strong>struct</strong> RootView: <em>View</em> {<br>  <strong>var</strong> body: <strong>some</strong> <em>View</em> {<br>    NavigationView {<br>      Text(&quot;Content&quot;)<br>        .navigationTitle(&quot;Title&quot;)<br>    }<br>  }<br>}</pre><p>That .navigationTitle does not directly affect the text it is attached to, but instead sets the title of the navigation bar. This would not be possible without PreferenceKey because normally information flows down the view heirarchy. And modifiers only affect the container to which they are attached. But the navigationTitle modifier is sending the string up the flow to a view that isn’t even a part of the body.</p><p>I spent a while trying to figure out when you’d ever really want to do something like this in the real world. I mean, if you intelligently composed your SwiftUI, something like this shouldn’t really ever be necessary.</p><p>I did find one potential use case, and if you’re interested, keep reading…</p><h4>A PreferenceKey experiment</h4><p>If you’ve used our Ancestry app recently, you’ve hopefully noticed a new feature that allows you to create stories based on people, photos or events from your tree.</p><p>This “story builder” includes a number of slide templates that the author can add to their story, for example, BuilderTextSlide. The templates share common “editing” functionality which is stored in a different view called EditableSlide. EditableSlide includes a number of things, the most important of which is a “Done” button, which saves the slide when it is done being created. In order for each template to access the “editable” features, the slides are defined like this:</p><pre>struct BuilderTextSlide: View {<br>  @State var text: String<br>  var body: some View {<br>    EditableSlide {<br>      TextEditor(text: text)<br>      // The structure of BuilderTextSlide is much more complicated than this, but this gives you an idea<br>    }<br>  }<br>}</pre><p>And EditableSlide is defined like this:</p><pre>struct EditableSlide&lt;Content: View&gt;: View {</pre><pre>private let content: Content</pre><pre>init(@ViewBuilder content: () -&gt; Content) {<br>  self.content = content()<br>}</pre><pre>var body: some View {<br>  ZStack {<br>    content<br>      .zIndex(0)<br>    VStack {<br>      HStack {<br>        Spacer()<br>          Button(&quot;Done&quot;) {<br>            // save the slide<br>          }<br>        }<br>        Spacer()<br>      }<br>      .zIndex(1)<br>    }<br>  }<br>}</pre><blockquote>EditableSlide is a “view builder”. Defining how a view builder works is outside the scope of this article. For more information, check out <a href="https://swiftontap.com/viewbuilder">https://swiftontap.com/viewbuilder</a></blockquote><p>Since the “Done” button is part of EditableSlide, the text slide itself does not know when the button is tapped. But sometimes we want the slide to do some extra, slide specific, work in response to the button tap. And this is where PreferenceKey <em>could</em> come into play. We essentially just need a way to send information that the button was tapped up to BuilderTextSlide.</p><p>Here’s how this could work using PreferenceKey:</p><pre>struct Slide: View {<br>  <a href="http://twitter.com/State">@State</a> private var tapCount = 0<br>  var body: some View {<br>    EditableSlide {<br>      Text(&quot;Tap count \(tapCount)&quot;)<br>    }<br>    .onPreferenceChange(TapPreferenceKey.self) { value in<br>      tapCount += 1<br>    }<br>  }<br>}</pre><pre>struct EditableSlide&lt;Content: View&gt;: View {<br>    <br>  let content: Content<br>  <a href="http://twitter.com/State">@State</a> private var tapped = false<br>    <br>  init(<a href="http://twitter.com/ViewBuilder">@ViewBuilder</a> content: () -&gt; Content) {<br>    self.content = content()<br>  }</pre><pre>  var body: some View {<br>    VStack {<br>      content<br>      Button(&quot;Tap&quot;) {<br>        tapped.toggle()<br>      }<br>      .preference(key: TapPreferenceKey.self, value: tapped)<br>    }<br>  }<br>}</pre><pre>struct TapPreferenceKey: PreferenceKey {<br>    static var defaultValue: Bool = false<br>    static func reduce(value: inout Bool, nextValue: () -&gt; Bool) {<br>        value = nextValue()<br>    }<br>}</pre><p>Create a preference key called TapPreferenceKey, bind it to a state variable, and whenever that state changes, TapPreferenceKey will “change”. Then you can react to that change via the .onPreferenceChange modifier.</p><p>This can all also be done via bindings like this:</p><pre>struct Slide2: View {<br>  <a href="http://twitter.com/State">@State</a> private var tapped = false<br>  @<a href="http://twitter.com/State">State</a> private var tapCount = 0<br>  var body: some View {<br>    EditableSlide2(tapped: $tapped) {<br>      Text(&quot;Tap count \(tapCount)&quot;)<br>    }<br>    .onChange(of: tapped) { _ in<br>      tapCount += 1<br>    }<br>  }<br>}</pre><pre>struct EditableSlide2&lt;Content: View&gt;: View {<br>    <br>  let content: Content<br>  <a href="http://twitter.com/Binding">@Binding</a> var tapped: Bool<br>    <br>  init(tapped: Binding&lt;Bool&gt;, <a href="http://twitter.com/ViewBuilder">@ViewBuilder</a> content: () -&gt; Content) {<br>    self._tapped = tapped<br>    self.content = content()<br>  }<br>    <br>  var body: some View {<br>    VStack {<br>      content<br>      Button(&quot;Tap&quot;) {<br>        tapped.toggle()<br>      }<br>    }<br>  }<br>}</pre><p>Using bindings is technically less code, plus you don’t need to clutter it up with custom preference keys.</p><p>In closing, preference keys are very useful for grabbing the size and origin of views. But past that, I don’t know of a good use for them. Maybe you do! If so, please let us know in the comments!</p><p><em>If you’re interested in joining Ancestry, we’re hiring! Feel free to check out our careers page for </em><a href="https://careers.ancestry.com/"><em>more info</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360505ff8fbb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-preferencekey-360505ff8fbb">SwiftUI Pro Tips: PreferenceKey</a> was originally published in <a href="https://medium.com/ancestry-product-and-technology">Ancestry Product &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Pro Tips 4–6]]></title>
            <link>https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-4-6-4139efd1d087?source=rss-29096ae0f03d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4139efd1d087</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ancestry]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Ryan Jennings]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 21:11:55 GMT</pubDate>
            <atom:updated>2022-04-26T21:11:55.641Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is part of a series on SwiftUI pro tips. To read the first article, <a href="https://medium.com/ancestry-engineering/swiftui-pro-tips-1-3-b03611fd9e4f">click here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70lkYsCfCt2AdpzvQIeutQ.png" /></figure><h4>Pro tip #4: Iterate Binding Array</h4><p><em>(Some backstory on this tip. At Ancestry we hold hackathons a couple times a year where developers form teams and work on fun projects. We’ve also recently launched a tool to allow Ancestry users to build stories in the mobile apps. For a recent hackathon I developed a way for users to add stickers to the “slides” that make up their stories.)</em></p><p>As of Swift 5.5, you can now iterate through an array of bindings and extract each individual binding to use as you will. I did this when creating the UGC Stickers demo. Here’s how it’s done:</p><pre>@Binding var stickers: [UGCStickerData]</pre><pre>ForEach($stickers, id: \.id) { $data in<br>  UGCSticker($data)<br>    .frame(width: 100, height: 100)<br>}</pre><p>I took this approach because each slide was responsible for maintaining the array of stickers that were added to the slide. But the logic for moving, scaling and rotating each sticker was part of theUGCSticker struct. So I would instantiate UGCStickerData on the slide, add it to the stickers array, and then pass the sticker data to the sticker struct for it to manipulate however it wanted. Since it was a shared binding, whenever the sticker was modified (moved, rotated, scaled), the data was both updated within the sticker itself (to maintain state) <strong>and</strong> modified in the array stored on the slide. This made it easy to save the sticker data along with the other slide data when necessary. Previous to Swift 5.5, you had to use custom bindings like this:</p><pre>ForEach(stickers.indices, id:\.self ) { index in<br>  UGCSticker(Binding(<br>    get: { return stickers[index] },<br>    set: { (newValue) in return self.stickers[index] = newValue}<br>  ))<br>}</pre><p>Much easier now.</p><h4>Pro Tip #5: EnvironmentObject</h4><p>As you develop larger, more complex, interfaces in SwiftUI, there will be common properties that you will want different structs/views to reference. You could pass them from one struct to another through each struct’s initializer, but there’s a much easier way to make common variables accessible. First, define a class as an ObservableObject:</p><pre>class StoryBuilderState: ObservableObject {   <br>   @Published var currentSlideIndex = 0<br>   @Published var isEditing = false<br>   @Published var hasEdited = false<br>}</pre><p>Then, in your main struct (the view that is shown first, also sometimes called the ancestor view), define a variable that will hold the ObservableObject:</p><pre>@ObservedObject var state: StoryBuilderState</pre><p>And add that variable as an environment object to the body of the main view struct:</p><pre>public var body: some View {<br>   ZStack {<br>      SomeInnerView()<br>   }<br>   .environmentObject(state)<br>}</pre><p>Now, without explicitly passing the variables, you can reference any of the observable object’s variables from within other structs by declaring an environment object within that struct:</p><pre>struct SomeInnerView: View {<br>   @EnvironmentObject var state: StoryBuilderState<br>...</pre><p>The @Published variables from the ObservableObject will act as bindings, and so SomeInnerView will instantly know when isEditing is updated, for example. Used correctly, environment objects will declutter your code from the unnecessary back and forth passing of variables.</p><p>For more on environment objects: <a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views">https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views</a></p><h4>Pro Tip #6: contentShape()</h4><p>You can make anything tappable by adding an .onTapGesture to the element. For example:</p><pre>Text(&quot;Some text&quot;)<br>   .onTapGesture {<br>      print(&quot;Do something&quot;)<br>   }</pre><p>When you add a tap gesture to text, the gesture is applied to the entire text, meaning you can tap on any of the words that comprise the text and the action associated with the gesture will be fired. But let’s imagine you’ve created a List. A list acts much like a UIKit UITableView and displays one row after another vertically. Let’s say each of these rows had some text and you wanted to allow the user to select a row by tapping anywhere on the row.</p><pre>List {<br>   ForEach(0..&lt;10) { i in<br>      Text(&quot;This is row \(i)&quot;)<br>         .onTapGesture {<br>            print(&quot;Do something&quot;)<br>         }<br>   }<br>}</pre><p>Now the text essentially makes up the entire row (programmatically). If you were to apply the tap gesture to the Text (like above), you may be surprised to find out that the tap gesture only works if you tap directly on the text. Tapping anywhere else on the row, an area that does not display text, does nothing. Why is this? Because the gesture is only added to the parts of the container that display something. The empty parts of the row, that are not filled with words, will remain action-less. How can we change the tappable area? One way would be to wrap the Text in an HStack and then apply the tap gesture to the HStack:</p><pre>HStack {<br>   Text(type)<br>   Spacer() // fill out empty space to make row full width<br>}<br>.onTapGesture {<br>   print(&quot;Do something&quot;)<br>}</pre><p>But this still doesn’t work because the tap gesture is still only applied to the parts of the container that display something. A spacer displays nothing, it just fills space. To change the “shape” of the tappable area, you need to use contentShape. By adding a content shape to the HStack, the tappable area will not just comprise what’s displayed by the HStack, but will instead encompass the entire <strong>bounds</strong> of the HStack. And yes, you still need the spacer because without it the HStack would only be as large as the text it displays, not the full width of the row. Here’s the full code:</p><pre>List {<br>   ForEach(0..&lt;10) { i in<br>      HStack {<br>         Text(&quot;This is row \(i)&quot;)<br>         Spacer() // fill out empty space to make row full width<br>      }<br>      .contentShape(Rectangle())<br>      .onTapGesture {<br>         print(&quot;Do something&quot;)<br>      }<br>   }<br>}</pre><p>For more information on contentShape: <a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape">https://www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape</a></p><p><em>If you’re interested in joining Ancestry, we’re hiring! Feel free to check out our careers page for </em><a href="https://careers.ancestry.com/"><em>more info</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4139efd1d087" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-4-6-4139efd1d087">SwiftUI Pro Tips 4–6</a> was originally published in <a href="https://medium.com/ancestry-product-and-technology">Ancestry Product &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Pro Tips 1–3]]></title>
            <link>https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-1-3-b03611fd9e4f?source=rss-29096ae0f03d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03611fd9e4f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ryan Jennings]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 16:53:23 GMT</pubDate>
            <atom:updated>2022-04-06T16:53:23.952Z</atom:updated>
            <content:encoded><![CDATA[<p>At Ancestry we’ve been slowly transitioning to SwiftUI for our user interfaces and have picked up a couple of useful “pro tips” along the way. Here are a couple of these tips. I’ll follow up with more in the future.</p><blockquote>This article assumes you have a basic understanding of SwiftUI and its mechanics. If you are completely unfamiliar with SwiftUI, I recommend you visit Paul Hudson’s “100 Days of SwiftUI” <a href="https://www.hackingwithswift.com/100/swiftui">https://www.hackingwithswift.com/100/swiftui</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70lkYsCfCt2AdpzvQIeutQ.png" /></figure><h3><strong>Pro Tip #1: Initializing @State variables</strong></h3><p>Usually state variables are initialized inline when you declare them:</p><pre>@State private var speed: Double = 3.0</pre><p>But sometimes you need to set them based on a value passed through the init() function. So, you can do this instead:</p><pre>@State private var speed: Double<br>init(speed: Double) {<br>   self._speed = State(initialValue: speed)<br>}</pre><p>For more information on @State: <a href="https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-state-property-wrapper">https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-state-property-wrapper</a></p><h3><strong>Pro tip #2: Custom Bindings</strong></h3><p>Sometimes you’ll want to react to a binding when it’s updated. To do this, you can use the .onChange modifier:</p><pre>.onChange(of: &lt;binding&gt;) { &lt;binding value&gt; in<br>   &lt;do something&gt;<br>}</pre><p>But this is only fired after the binding is updated. What if you want to react when (or immediately before) a binding is updated? You can’t add a didSave or willSave to the binding declaration. The binded variable doesn’t really belong to the struct it’s defined in. It is rather a variable that is shared with that struct, from another struct (an ancestor struct) where the key variable is defined as something like @State. You <strong>can</strong> add a didSave to a @State variable, but for a binding you have to get a little more creative.</p><p>Here’s what I did. I wanted a text binding (attached to a TextEditor) to limit its size to a certain number of characters. If I used onChange, and the user typed within the text editor, the character that was over the limit was allowed to be typed, but then would disappear. I instead wanted a hard stop, when you’re at the character limit future typing should just be blocked.To achieve this I created a custom binding. The “true” binding is defined as you normally would:</p><pre>@Binding public var text: String</pre><p>Then I declare another “custom” binding that sets and returns the value of the “true” binding, but whose “set” function is called when the custom binding is being set. And so further processing can happen at that time, and in my case I could limit the string to a certain number of characters.</p><pre>let textCustomBinding = Binding(<br>   get: { self.text },<br>   set: { self.text = String($0.prefix(200)).components(separatedBy: .newlines).joined() }<br>)</pre><p>My TextEditor then uses this custom binding instead of the true binding:</p><pre>TextEditor(text: textCustomBinding)</pre><p>And this allowed the text editor to behave exact how I wanted it to.</p><p>For more information on custom bindings: <a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-custom-bindings">https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-custom-bindings</a></p><h3><strong>Pro tip #3: Dynamic TextEditor</strong></h3><p>By default a TextEditor will take up as much room as possible. It will fill all the available space of its parent. To limit the size of a TextEditor, apply a .frame(width: &lt;value&gt;, height: &lt;value&gt;) modifier.</p><p>But if you want the TextEditor to only be as tall as the amount of text typed into it, and grow as more text is entered, place the TextEditor inside the .overlay modifier of a Text view. The Text view will only display as tall as the amount of text it needs to display, and the embedded TextEditor will only fill that amount of space. And since both are sharing the same text @State variable, both will &quot;grow&quot; as more text is added to the variable.</p><pre>@State private var text = &quot;&quot;</pre><pre>...</pre><pre>Text(text) // This transparent text view is used to size the text editor<br>   .font(font)<br>   .foregroundColor(.clear)<br>   .padding(.horizontal, 5)<br>   .padding(.vertical, 8) // This padding is to match the default padding of TextEditor<br>   .frame(maxWidth: .infinity)<br>   .background(Color.clear)<br>   .overlay(<br>      TextEditor(text: text)<br>         .font(font)<br>   )</pre><blockquote>Come back next week for more pro tips!</blockquote><h3>Bonus!</h3><p>Here is a handy SwiftUI cheat sheet originally provided by Jared Sinclair (but slightly modified by one of our SwiftUI engineers, Scott Doerrfeld):</p><p><a href="https://jaredsinclair.com/2020/05/07/swiftui-cheat-sheet.html">https://jaredsinclair.com/2020/05/07/swiftui-cheat-sheet.html</a></p><p><strong>SwiftUI Cheat Sheet</strong></p><ol><li>Use @State when your view needs to mutate one of its own properties.</li><li>Use @Binding when your view needs to mutate a property owned by an ancestor view, or owned by an observable object that an ancestor has a reference to.</li><li>Use @StateObject when your view instantiates an observable object itself.</li><li>Use @ObservedObject when your view is dependent on an observable object that gets passed into that view’s initializer.</li><li>Use @EnvironmentObject when it would be too cumbersome to pass an observable object through all the initializers of all your view’s ancestors.</li><li>Use @Environment when your view is dependent on a type that cannot conform to ObservableObject.</li><li>Also use @Environment when your views are dependent upon more than one instance of the same type, as long as that type does not need to be used as an observable object.</li><li>If your view needs more than one instance of the same observable object class, you are out of luck. You cannot use @EnvironmentObject nor @Environment to resolve this issue.</li></ol><p><em>If you’re interested in joining Ancestry, we’re hiring! Feel free to check out our careers page for </em><a href="https://careers.ancestry.com/"><em>more info</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03611fd9e4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ancestry-product-and-technology/swiftui-pro-tips-1-3-b03611fd9e4f">SwiftUI Pro Tips 1–3</a> was originally published in <a href="https://medium.com/ancestry-product-and-technology">Ancestry Product &amp; Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>