网上关于定制macOS-toolbar的文章都比较老,这篇文章讲下如何用swiftUI修改toolbar,比较推荐方法二。
方法一:
在Appdelegate文件里加上
let titlebarAccessoryView = TitlebarAccessory().padding([.top, .leading, .trailing], 16.0).edgesIgnoringSafeArea(.all)
let accessoryHostingView = NSHostingView(rootView:titlebarAccessoryView)
accessoryHostingView.frame.size = accessoryHostingView.fittingSize
let titlebarAccessory = NSTitlebarAccessoryViewController()
titlebarAccessory.view = accessoryHostingView
titlebarAccessory.layoutAttribute = .trailing
以及
window.addTitlebarAccessoryViewController(titlebarAccessory)
新建一个TitlebarAccessory.swift的文件,内容如下:
import SwiftUI
struct TitlebarAccessory: View {
var body: some View {
Text("hello")
}
}
运行