我正在尝试将我的macOS应用程序的UI在StoryBoard中写入SwiftUI。我是SwiftUI的初学者...
我有swiftUI Picker如下:
import SwiftUI
struct MessageAreaView: View {
// opponent name
@ObservedObject var anOpponentName: ShareValues
// menu type picker selection
@State var selectedMenu: String = ""
// menu type picker content
let defaultMenus = ["Hi. How about a game?", "Good luck!", "I give in.", "Thank you for the game.", "Let’s play again sometime.", "My hand slipped. May I undo?", "Hello.", "Goodby.", "Thanks."]
var body: some View {
// Menu type picker
Picker(selection: $selectedMenu, label: Text(""), content: {
Text("Select Item").tag("") // To avoid "picker: the selection "" is invalid..."
ForEach(defaultMenus, id:\.self) { aMenu in
Text(aMenu)
}
})
.pickerStyle(.menu)
.onChange(of: selectedMenu, perform: { selected in
if !(selected == NSLocalizedString("Select Item", comment: "Select Item")) {
let anOpponent = anOpponentName.anOpponentName
let commentToSend = NSString(format: "TELL %@ %@\r\n", anOpponent, selected) as String
mySocket.sendMessage(message: commentToSend)
}
// I'd like to set selectedMenu to "Select Item" here...
})
.frame(width:470)
}
我想将selectedMenu设置为“Select Item”(选择器选择的第一项)。使用NSPopUpButton,有selectItem(位于:index),但是我在SwiftUI Picker中找不到这样做的方法...我该怎么做呢?
1条答案
按热度按时间4ngedf3f1#
首先,比较
selected == NSLocalizedString("Select Item"
将始终是false
,因为"Select Item"
是菜单项的显示标题,而不是空字符串的值/标签。其次,
Swift
提供了一种更方便的格式化字符串的方法,称为String Interpolation。要将选择器重置为
"Select Item"
,请将属性selectedMenu
设置为空字符串。