lgm0905
lgm0905

Reputation: 145

What is the role of tag in SwiftUI?

I'm confused of role of tag. When I remove tag, I can pick only "M", and add, I can pick all options.

When I made Integer array picker, the presence of tag don't matter at all.

But The problem occurs in String array. And I want to know why this things happen.

import SwiftUI

struct InitGender: View {
    @ObservedObject var initData : InitData
    @ObservedObject var initViewRouter : InitViewRouter
    let genderRange = ["M","F"]
    
    var body: some View {
        VStack {
            Text("Select your gender")
                .font(.title)
                .bold()
            
            Picker("Select gender", selection : $initData.gender) {
                ForEach(0..<genderRange.count) {
                    Text(self.genderRange[$0]).tag(self.genderRange[$0])
                }
            }
            .labelsHidden()
            .clipped()
        }
    }    
}

Upvotes: 12

Views: 10996

Answers (1)

Asperi
Asperi

Reputation: 258345

SwiftUI Picker detects selection either by tag or by id, for this types of selection and tag (or id) must be the same.

Here is a demo (tested with Xcode 12 / iOS 14)

struct InitGender: View {
    @State private var selection: String = "M"
    let genderRange = ["M","F"]

    var body: some View {
        VStack {
            Text("Select your gender")
                .font(.title)
                .bold()
            Text("Selected: \(selection)")

            Picker("Select gender", selection : $selection) {
                ForEach(0..<genderRange.count) {
                    Text(self.genderRange[$0]).tag(self.genderRange[$0])
                }
            }
            .labelsHidden()
            .clipped()
       }
   }
}

alternate working variant of Picker

Picker("Select gender", selection : $selection) {
    ForEach(genderRange, id: \.self) {
        Text($0)
    }
}

Add-on: important parts of tag documentation:

/// Use this modifier to differentiate among certain selectable views,
/// like the possible values of a ``Picker`` or the tabs of a ``TabView``.


/// A ``ForEach`` automatically applies a default tag to each enumerated
/// view using the `id` parameter of the corresponding element. If
/// the element's `id` parameter and the picker's `selection` input
/// have exactly the same type, you can omit the explicit tag modifier.

Upvotes: 16

Related Questions