Swift学习笔记:swiftui修改toolbar/titlebar
程序员文章站
2024-03-24 12:59:16
...
let contentView = ContentView().environment(\.managedObjectContext, persistentContainer.viewContext).frame(minWidth: 450, maxWidth: .infinity, minHeight: 400, maxHeight: .infinity)
// Create the titlebar accessory
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
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.setFrame(CGRect(x: 10, y: 10, width: 550, height: 650), display: true)
window.center()
window.addTitlebarAccessoryViewController(titlebarAccessory)
window.backgroundColor = NSColor.white
//window.minSize = NSSize(width: 500, height: 400)
//window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
在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")
}
}
运行