Instance Method インスタンスメソッド

tag(_:)

Sets the unique tag value of this view. このビューの固有タグ値を設定します。

Declaration 宣言

func tag<V>(_ tag: V) -> some View where V : Hashable

Return Value 戻り値

A view with the specified tag set. 指定されたタグを設定したあるビュー。

Parameters パラメータ

tag

A Hashable value to use as the view’s tag. ビューのもつタグとして使うことになるあるHashable値。

Discussion 議論

Use this modifier to differentiate among certain selectable views, like the possible values of a Picker or the tabs of a TabView. Tag values can be of any type that conforms to the Hashable protocol.

In the example below, the ForEach loop in the Picker view builder iterates over the Flavor enumeration. 下の例において、ForEachループはPickerビュービルダーの中で、Flavor列挙のすべてにわたって反復します。 It extracts the string value of each enumeration element for use in constructing the row label, and uses the enumeration value, cast as an optional, as input to the tag(_:) modifier. The Picker requires the tags to have a type that exactly matches the selection type, which in this case is an optional Flavor.


struct FlavorPicker: View {
    enum Flavor: String, CaseIterable, Identifiable {
        case chocolate, vanilla, strawberry
        var id: Self { self }
    }


    @State private var selectedFlavor: Flavor? = nil


    var body: some View {
        Picker("Flavor", selection: $selectedFlavor) {
            ForEach(Flavor.allCases) { flavor in
                Text(flavor.rawValue).tag(Optional(flavor))
            }
        }
    }
}

If you change selectedFlavor to be non-optional, you need to remove the Optional cast from the tag input to match.

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. To see examples that don’t require an explicit tag, see Picker.

See Also 参照

Identity