<?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 Julien Sagot on Medium]]></title>
        <description><![CDATA[Stories by Julien Sagot on Medium]]></description>
        <link>https://medium.com/@Barbapapapps?source=rss-cf68d3bbacc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WzqRRdbEj0jVVVCH.jpg</url>
            <title>Stories by Julien Sagot on Medium</title>
            <link>https://medium.com/@Barbapapapps?source=rss-cf68d3bbacc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 05:44:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Barbapapapps/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[Beyond Basics: Implementing a custom Picker in SwiftUI]]></title>
            <link>https://medium.com/@Barbapapapps/beyond-basics-implementing-a-custom-picker-in-swiftui-88c01e283ac1?source=rss-cf68d3bbacc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c01e283ac1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Julien Sagot]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 18:31:23 GMT</pubDate>
            <atom:updated>2024-01-04T21:13:11.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced SwiftUI: Implementing a custom Picker</h3><p>Explore <strong>advanced SwiftUI techniques</strong> by implementing a custom <strong>Picker</strong>. While SwiftUI’s default system picker is <strong>powerful</strong>, developers often desire <strong>more flexibility</strong> in <strong>design</strong> and <strong>behavior</strong>.</p><p>This article assumes <strong>familiarity</strong> with <strong>SwiftUI’s core principles</strong> and dives into creating a custom value picker for <strong>tailored aesthetics</strong> and <strong>enhanced control</strong>.</p><h3>💭 Outlining the API</h3><p>When creating components, I always initiate the process by <strong>outlining the intended API</strong>. This foundational step is <strong>crucial</strong>, as it prompts <strong>thoughtful consideration</strong> of the necessary actions to attain the <strong>desired API</strong>.</p><p>In this case, <strong>simplicity</strong> is key; we aim for an API closely resembling the system’s <a href="https://developer.apple.com/documentation/swiftui/picker">Picker API</a>:</p><pre>Picker(&quot;Flavor&quot;, selection: $selectedFlavor) {<br>    ForEach(Flavor.allCases) { flavor in<br>        Text(flavor.rawValue.capitalized)<br>    }<br>}</pre><p>Wouldn’t it be wonderful if we could replicate the same API for our custom ValuePicker component? Let’s take a closer look and explore the possibilities.</p><pre>ValuePicker(&quot;Label&quot;, selection: $selection) {<br>  ForEach(values) { value in<br>    Text(value)<br>  }<br>}</pre><h3>🔨 Defining the view and its initializer</h3><pre>public struct ValuePicker&lt;SelectionValue: Hashable, Content: View&gt;: View {<br>  private let title: LocalizedStringKey<br>  private let selection: Binding&lt;SelectionValue&gt;<br>  private let content: Content<br><br>  public init(<br>    _ title: LocalizedStringKey,<br>    selection: Binding&lt;SelectionValue&gt;,<br>    @ViewBuilder content: () -&gt; Content<br>  ) {<br>    self.title = title<br>    self.selection = selection<br>    self.content = content()<br>  }<br>}</pre><p>The view has to be <strong>generic</strong> over <strong>two types</strong>: SelectionValue, representing the type of <strong>the value we can select</strong>, and Content, which will encompass the <strong>set of possible options</strong>.</p><p>At the call-site, this would result in the following:</p><pre>ValuePicker(&quot;Name&quot;, selection: $name) {<br>  ForEach(names) { name in<br>    Text(name)<br>  }<br>}</pre><p>So far, everything is smooth and straightforward — no complications or issues to address. Next, let&#39;s implement the view&#39;s body.</p><h3>🩻 The view&#39;s body</h3><pre>public var body: some View {<br>  NavigationLink {<br>    List {<br>      content<br>    }<br>    .navigationTitle(label)<br>  } label: {<br>    VStack {<br>      Text(title)<br>        .font(.footnote.weight(.medium))<br>        .foregroundStyle(.secondary)<br><br>      Text(verbatim: String(describing: selection.wrappedValue))<br>    }<br>  }<br>}</pre><p>Which, within a list, renders like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*eY3nLmFJt0XlH51ouRMUCA.gif" /></figure><pre>#Preview {<br>  NavigationStack {<br>    List {<br>      ValuePicker(&quot;Name&quot;, selection: .constant(&quot;John&quot;)) {<br>        ForEach([&quot;John&quot;, &quot;Jean&quot;, &quot;Juan&quot;]) { name in<br>          Text(verbatim: name)<br>        }<br>      }<br>    }<br>    .navigationTitle(&quot;Custom Picker&quot;)<br>  }<br>}</pre><p>That’s pretty cool; with a small amount of code, we’re now able to push a list of options. However, two key features are missing: when we push the options, it’s not clear which <strong>value is currently selected</strong>, and we also can’t really <strong>change the selection</strong>, which is the main purpose of a picker component 😅.</p><p>There’s a problem, though; we get access to the options through a <strong>single view</strong> (content). Since it’s constructed within a @ViewBuilder closure, we lack the ability to <strong>access individual options</strong>.</p><h3>🛟 _VariadicView to the rescue</h3><p>Have you ever heard of the _VariadicView? If you haven’t, I would suggest you read this <a href="https://movingparts.io/variadic-views-in-swiftui">fantastic article</a> on the topic by Moving Parts.</p><p>In short, _VariadicView is an <strong>undocumented</strong> view capable of <strong>destructuring</strong> another view to access its child views.</p><p>We’re going to leverage its power to <strong>add a checkmark</strong> next to the selected row and make the rows <strong>interactive</strong> so we can finally <strong>change the selection</strong>.</p><pre>private struct ValuePickerOptions&lt;Value: Hashable&gt;: _VariadicView.MultiViewRoot {<br>  private let selectedValue: Binding&lt;Value&gt;<br><br>  init(selectedValue: Binding&lt;Value&gt;) {<br>    self.selectedValue = selectedValue<br>  }<br><br>  @ViewBuilder<br>  func body(children: _VariadicView.Children) -&gt; some View {<br>    Section {<br>      ForEach(children) { child in<br>        ValuePickerOption(selectedValue: selectedValue) {<br>          child<br>        }<br>      }<br>    }<br>  }<br>}<br><br>private struct ValuePickerOption&lt;Content: View, Value: Hashable&gt;: View {<br>  @Environment(\.dismiss) private var dismiss<br><br>  private let selectedValue: Binding&lt;Value&gt;<br>  private let content: Content<br><br>  init(<br>    selectedValue: Binding&lt;Value&gt;, <br>    @ViewBuilder _ content: () -&gt; Content<br>  ) {<br>    self.selectedValue = selectedValue<br>    self.content = content()<br>  }<br><br>  var body: some View {<br>    Button(<br>      action: {<br>        selectedValue.wrappedValue = ❓❓❓  // What value should we set here?<br>        dismiss()<br>      },<br>      label: {<br>        HStack {<br>          content<br>            .tint(.primary)<br>            .frame(maxWidth: .infinity, alignment: .leading)<br><br>          if isSelected {<br>            Image(systemName: &quot;checkmark&quot;)<br>              .foregroundStyle(.tint)<br>              .font(.body.weight(.semibold))<br>              .accessibilityHidden(true)<br>          }<br>        }<br>        .accessibilityElement(children: .combine)<br>        .accessibilityAddTraits(isSelected ? .isSelected : [])<br>      }<br>    )<br>  }<br><br>  private var isSelected: Bool {<br>    // How to determine whether that option is currently selected?<br>    return ❓❓❓<br>  }<br>}</pre><p>Alright, that&#39;s quite a lot of code 😅 <br>To summarize, ValuePickerOptions takes a view and <strong>destructures</strong> it in its <strong>body</strong>. We take this opportunity to <strong>wrap</strong> every child into a ValuePickerOption view (which itself wraps the child within a Button) so we can customize the UI and behavior.</p><p>We now have <strong>another problem</strong>, how do we access the <strong>value associated</strong> with each option? 🤔<br>Seems like we’re stuck here.</p><p>How on earth is the system component doing it? Well, the <a href="https://developer.apple.com/documentation/swiftui/picker">documentation</a> gives us the answer:</p><blockquote>ForEach automatically assigns a tag to the selection views using each option’s id.</blockquote><p>So it seems like Apple is <strong>injecting a tag</strong> into each <strong>view</strong>. We can indeed confirm this hypothesis by looking at <a href="https://gist.github.com/Cosmo/8349dc9957e8e27ae3d3bd0ffe43a250">SwiftUI’s headers</a>:</p><pre>extension View {<br>  @inlinable public func tag&lt;V&gt;(_ tag: V) -&gt; some View where V : Hashable {<br>    return _trait(TagValueTraitKey&lt;V&gt;.self, .tagged(tag))<br>  }<br>  <br>  @inlinable public func _untagged() -&gt; some View {<br>    return _trait(IsAuxiliaryContentTraitKey.self, true)<br>  }<br>  <br>}<br>@usableFromInline<br>internal struct TagValueTraitKey&lt;V&gt; : _ViewTraitKey where V : Hashable {<br>  @usableFromInline<br>  @frozen internal enum Value {<br>    case untagged<br>    case tagged(V)<br>  }<br>  @inlinable internal static var defaultValue: TagValueTraitKey&lt;V&gt;.Value {<br>    get { .untagged }<br>  }<br>}<br>@usableFromInline<br>internal struct IsAuxiliaryContentTraitKey : _ViewTraitKey {<br>  @inlinable internal static var defaultValue: Bool {<br>    get { false }<br>  }<br>  @usableFromInline<br>  internal typealias Value = Bool<br>}</pre><p>Unfortunately, TagValueTraitKey is <strong>not publicly exposed</strong>, so we can&#39;t use it. Nevertheless, let&#39;s <strong>implement our own</strong>!</p><h3>💉 Custom Tag Injection</h3><pre>private struct CustomTagValueTraitKey&lt;V: Hashable&gt;: _ViewTraitKey {<br>  enum Value {<br>    case untagged<br>    case tagged(V)<br>  }<br><br>  static var defaultValue: CustomTagValueTraitKey&lt;V&gt;.Value {<br>    .untagged<br>  }<br>}<br><br>extension View {<br>  public func pickerTag&lt;V: Hashable&gt;(_ tag: V) -&gt; some View {<br>    _trait(CustomTagValueTraitKey&lt;V&gt;.self, .tagged(tag))<br>  }<br>}</pre><p>With those being created, we can now <strong>inject a custom trait</strong> inside our ForEach. We could also have created a special version of ForEach to do it automatically, but I feel like the <strong>custom view extension</strong> is a good <strong>compromise</strong>:</p><pre>NavigationStack {<br>  List {<br>    ValuePicker(&quot;Name&quot;, selection: .constant(&quot;John&quot;)) {<br>      ForEach([&quot;John&quot;, &quot;Jean&quot;, &quot;Juan&quot;]) { name in<br>        Text(verbatim: name)<br>          .pickerTag(name) // 🟢🟢🟢<br>        }<br>      }<br>    }<br>    .navigationTitle(&quot;Custom Picker&quot;)<br>  }<br>}</pre><p>Each tag can be retrieved through the _VariadicView_Children.Element using the <strong>subscript syntax</strong>. We&#39;ll pass it into the ValuePickerOption view:</p><pre>private struct ValuePickerOptions&lt;Value: Hashable&gt;: _VariadicView.MultiViewRoot {<br>  ...<br><br>  @ViewBuilder<br>  func body(children: _VariadicView.Children) -&gt; some View {<br>    Section {<br>      ForEach(children) { child in<br>        ValuePickerOption(<br>          selectedValue: selectedValue,<br>          value: child[CustomTagValueTraitKey&lt;Value&gt;.self] // 🟢🟢🟢<br>        ) {<br>          child<br>        }<br>      }<br>    }<br>  }<br>}<br><br>private struct ValuePickerOption&lt;Content: View, Value: Hashable&gt;: View {<br>  ...<br>  private let value: Value?<br>  ...<br><br>  init(<br>    selectedValue: Binding&lt;Value&gt;,<br>    value: CustomTagValueTraitKey&lt;Value&gt;.Value, // 🟢🟢🟢<br>    @ViewBuilder _ content: () -&gt; Content<br>  ) {<br>    self.selectedValue = selectedValue<br>    self.value = if case .tagged(let tag) = value {<br>      tag<br>    } else {<br>      nil<br>    }<br>    self.content = content()<br>  }<br><br>  var body: some View {<br>    ...<br>  }<br><br>  private var isSelected: Bool {<br>    selectedValue.wrappedValue == value<br>  }<br>}</pre><h3>🦾 Wrapping it up</h3><p>Let&#39;s now wrap it up and use our ValuePickerOptions view within our ValuePicker:</p><pre>public var body: some View {<br>  NavigationLink {<br>    List {<br>      _VariadicView.Tree(ValuePickerOptions(selectedValue: selection)) {<br>        content<br>      }<br>    }<br>    ...<br>  } label: {<br>    ...<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*R6FWhxI8I2OCXL6wy-YqPA.gif" /><figcaption>Our custom picker is now fully implemented!</figcaption></figure><p>This is how it looks from the call-site:</p><pre>ValuePicker(&quot;Name&quot;, selection: $selection) {<br>  ForEach([&quot;John&quot;, &quot;Jean&quot;, &quot;Juan&quot;]) { name in<br>    Text(verbatim: name)<br>      .pickerTag(name)<br>  }<br>}</pre><p>Not bad, huh? It looks <strong>almost identical</strong> to the API we envisioned earlier! 💪</p><p>From now on, the possibilities are endless. You can tweak the implementation to allow <strong>multiple selections</strong>, <strong>empty value selection</strong>, and more.</p><p>📝 You can find the full code <a href="https://gist.github.com/juliensagot/42c7febb1418b5f58a8b1702793a6a73">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c01e283ac1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>