69 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			Swift
		
	
	
	
	
	
			
		
		
	
	
			69 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			Swift
		
	
	
	
	
	
| //
 | ||
| //  WindowSizeManager.swift
 | ||
| //  TeachMate
 | ||
| //
 | ||
| //  Created by Hongli on 2025/3/13.
 | ||
| //
 | ||
| 
 | ||
| import SwiftUI
 | ||
| 
 | ||
| #if os(macOS)
 | ||
| // 窗口尺寸管理器
 | ||
| struct WindowSizeManager {
 | ||
|     enum WindowSizePreset {
 | ||
|         case calendar  // 教学历视图 - 竖长
 | ||
|         case schedule  // 课表视图 - 横长
 | ||
|         
 | ||
|         var size: CGSize {
 | ||
|             switch self {
 | ||
|             case .calendar:
 | ||
|                 return CGSize(width: 500, height: 800)  // 竖长窗口
 | ||
|             case .schedule:
 | ||
|                 return CGSize(width: 1200, height: 680)  // 横长窗口
 | ||
|             }
 | ||
|         }
 | ||
|     }
 | ||
|     
 | ||
|     // 调整窗口大小
 | ||
|     static func resizeWindow(to preset: WindowSizePreset) {
 | ||
|         guard let window = NSApplication.shared.windows.first else { return }
 | ||
|         
 | ||
|         let newSize = preset.size
 | ||
|         let currentFrame = window.frame
 | ||
|         
 | ||
|         // 计算新的窗口位置,保持窗口中心点不变
 | ||
|         let newOriginX = currentFrame.origin.x + (currentFrame.width - newSize.width) / 2
 | ||
|         let newOriginY = currentFrame.origin.y + (currentFrame.height - newSize.height) / 2
 | ||
|         
 | ||
|         let newFrame = NSRect(
 | ||
|             x: newOriginX,
 | ||
|             y: newOriginY,
 | ||
|             width: newSize.width,
 | ||
|             height: newSize.height
 | ||
|         )
 | ||
|         
 | ||
|         // 平滑动画调整窗口大小
 | ||
|         window.animator().setFrame(newFrame, display: true, animate: true)
 | ||
|     }
 | ||
| }
 | ||
| 
 | ||
| // 视图修饰符,用于调整窗口大小
 | ||
| struct WindowSizeModifier: ViewModifier {
 | ||
|     let preset: WindowSizeManager.WindowSizePreset
 | ||
|     
 | ||
|     func body(content: Content) -> some View {
 | ||
|         content
 | ||
|             .onAppear {
 | ||
|                 WindowSizeManager.resizeWindow(to: preset)
 | ||
|             }
 | ||
|     }
 | ||
| }
 | ||
| 
 | ||
| // 扩展View以便于使用
 | ||
| extension View {
 | ||
|     func adjustWindowSize(to preset: WindowSizeManager.WindowSizePreset) -> some View {
 | ||
|         modifier(WindowSizeModifier(preset: preset))
 | ||
|     }
 | ||
| }
 | ||
| #endif
 |