實例方法
tag(_:)
設置此視圖的唯一標記值。
聲明
func tag<V>(_ tag: V) -> some View where V : Hashable
返回值
具有指定標記集的視圖。
參數
tag
用作視圖標記的
Hashable
詳述
使用此修飾符來區分某些可選視圖,例如 Picker
的可能值或 TabView
的選項卡。標簽值可以是任何符合
協議的類型。Hashable
在下麵的示例中,Picker
視圖構建器中的 ForEach
循環遍曆 Flavor
枚舉。它提取每個枚舉元素的字符串值以用於構造行標簽,並將枚舉值強製轉換為可選值,作為tag(_:)
修飾符的輸入。 Picker
要求標簽具有與選擇類型完全匹配的類型,在這種情況下是可選的 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))
}
}
}
}
如果將 selectedFlavor
更改為非可選,則需要從標簽輸入中刪除
強製轉換以匹配。Optional
ForEach
使用相應元素的id
參數自動將默認標記應用於每個枚舉視圖。如果元素的 id
參數和選擇器的 selection
輸入具有完全相同的類型,則可以省略顯式標記修飾符。要查看不需要顯式標記的示例,請參閱 Picker
。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Optional tabItem(_:)用法及代碼示例
- Swift Optional task(priority:_:)用法及代碼示例
- Swift Optional task(id:priority:_:)用法及代碼示例
- Swift Optional textSelection(_:)用法及代碼示例
- Swift Optional toolbar(id:content:)用法及代碼示例
- Swift Optional tint(_:)用法及代碼示例
- Swift Optional toolbar(content:)用法及代碼示例
- Swift Optional textContentType(_:)用法及代碼示例
- Swift Optional touchBarItemPresence(_:)用法及代碼示例
- Swift Optional touchBar(_:)用法及代碼示例
- Swift Optional touchBar(content:)用法及代碼示例
- Swift Optional toggleStyle(_:)用法及代碼示例
- Swift Optional transaction(_:)用法及代碼示例
- Swift Optional textInputAutocapitalization(_:)用法及代碼示例
- Swift Optional touchBarCustomizationLabel(_:)用法及代碼示例
- Swift Optional truncationMode(_:)用法及代碼示例
- Swift Optional transformEffect(_:)用法及代碼示例
- Swift Optional touchBarItemPrincipal(_:)用法及代碼示例
- Swift Optional symbolVariant(_:)用法及代碼示例
- Swift Optional popover(isPresented:attachmentAnchor:arrowEdge:content:)用法及代碼示例
- Swift Optional mask(alignment:_:)用法及代碼示例
- Swift Optional listSectionSeparatorTint(_:edges:)用法及代碼示例
- Swift Optional badge(_:)用法及代碼示例
- Swift Optional fullScreenCover(isPresented:onDismiss:content:)用法及代碼示例
- Swift Optional keyboardType(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional tag(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。