macOS获取屏幕窗口大小,获取宽度占窗口一半
鸣谢简书作者:原来你是这种花椒
就像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(@"窗口关闭"); }