SwiftUI: macOS toolbar is initially greyed out


Question


When I first launch my app the toolbar icons are shown and work fine, but they are initially greyed out until mousing over the button.

First run of the app:

and then mouse over:

Here is the code:

import SwiftUI

struct ContentView: View
{
    @State var mainList:[String] = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "Indigo", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whisky", "Xray", "Yankee", "Zulu"]
    @State var selectedItem:String? = "Echo"
    var body: some View
    {
        NavigationView
        {
            List()
            {
                ForEach(mainList, id: \.self)
                {item in
                    NavigationLink(destination: DetailView(item: item), tag: item, selection: $selectedItem, label:
                                    {
                                        Text("\(item)")
                                    })
                    
                }
            }
        }
        .toolbar
        {
            Button(action: {addNewItem()})
            {
                Label("Select", systemImage: "square.and.pencil")
            }
        }
        
    }
    
    func addNewItem()
    {
        print ("Add item")
    }
    
}

struct DetailView: View
{
    @State var item: String
    
    var body: some View
    {
        Text(item)
    }
}

This is in Xcode 12.5.1 and Xcode 13.0 beta.

I would have thought that the toolbar should be enabled at active with this code. Is it a bug or am I doing something wrong?


Answer 1:


Use ToolbarItem.

        .toolbar{
            ToolbarItem(placement: .primaryAction) {
                Button(action: {addNewItem()}){
                    Label("Select", systemImage: "square.and.pencil")
                }
            }
        }

https://developer.apple.com/documentation/swiftui/toolbaritem



来源:https://stackoverflow.com/questions/68312907/swiftui-macos-toolbar-is-initially-greyed-out


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者爷依然萧洒码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者爷依然萧洒码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: