鳴謝簡書作者:原來你是這種花椒
就像iOS獲取設備大小一樣,macOS的窗口大小就是我們所需要的代碼。
self.view.bounds.size.width
self.view.bounds.size.height
如果項目中使用Masonry插件,要獲取當前view的寬度那就是,高度同寬度修改即可
make.width.equalTo(self.view.mas_width).multipliedBy(0.5);//占屏幕寬度的一半
占屏幕寬度的一半再減去10
make.width.equalTo(ws.mas_width).multipliedBy(0.5).offset(-10);//占屏幕寬度的一半再減去10
我們在窗口變化的通知中監聽當前窗口大小,來決定控件的大小顯示。
交代清楚我們上代碼,先復制一段代碼運行感受一下。在從中選擇我們需要的的代碼。
#import "ViewController.h" #import <WebKit/WebKit.h> @interface ViewController () @property (nonatomic,strong)WKWebView * webView; @end @implementation ViewController -(void)viewDidLoad { [super viewDidLoad]; //觀察窗口拉伸 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenResize) name:NSWindowDidResizeNotification object:nil]; _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];//初始化 [self.view addSubview:_webView]; //1.網絡 _webView.allowsBackForwardNavigationGestures = YES; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.hao123.com/"]]; [_webView loadRequest:request]; } -(void)screenResize{ NSLog(@"觀察窗口拉伸"); NSLog(@"%.2f===%.2f",self.view.bounds.size.width,self.view.bounds.size.height); _webView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height); }
好,我們開始總結macOS開發監聽窗口的改變
1.觀察窗口的拉伸
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(screenResize) name:NSWindowDidResizeNotification object:nil]; -(void)screenResize{ NSLog(@"觀察窗口拉伸"); NSLog(@"%.2f===%.2f",self.view.bounds.size.width,self.view.bounds.size.height); }
2.即將進入全屏
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(willEnterFull:)
name:NSWindowWillEnterFullScreenNotification
object:nil]; -(void)willEnterFull:(NSNotification*)notification{ NSLog(@"即將全屏"); }
3.即將退出全屏
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(willExitFull:)
name:NSWindowWillExitFullScreenNotification
object:nil]; -(void)willExitFull:(NSNotification*)notification { NSLog(@"即將退出全屏"); }
4.已經退出全屏
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(didExitFull:)
name:NSWindowDidExitFullScreenNotification
object:nil]; -(void)didExitFull:(NSNotification*)notification{ NSLog(@"推出全屏"); }
5.窗口最小化
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(didMiniaturize:)
name:NSWindowDidMiniaturizeNotification
object:nil]; -(void)didMiniaturize:(NSNotification*)notification{ NSLog(@"窗口變小"); }
6.窗口即將關閉
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(willClose:)
name:NSWindowWillCloseNotification
object:nil]; -(void)willClose:(NSNotification*)notification{ NSLog(@"窗口關閉"); }