swift 如何让Picker的选中值成为首选

qojgxg4l  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(169)

我正在尝试将我的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中找不到这样做的方法...我该怎么做呢?

4ngedf3f

4ngedf3f1#

首先,比较selected == NSLocalizedString("Select Item"将始终是false,因为"Select Item"是菜单项的显示标题,而不是空字符串的值/标签。
其次,Swift提供了一种更方便的格式化字符串的方法,称为String Interpolation。
要将选择器重置为"Select Item",请将属性selectedMenu设置为空字符串。

.onChange(of: selectedMenu) { selected in
                
    if !selected.isEmpty {
        let anOpponent = anOpponentName.anOpponentName
        let commentToSend = "TELL \(anOpponent) \(selected)\r\n"
        mySocket.sendMessage(message: commentToSend)
        selectedMenu = ""
    }
}

相关问题