一直想实现微信的控制按钮,经历了太多的波折~
效果
-
非全屏
-
全屏
具体实现
1.storyboard中 window 的设置
2.viewcontroller
3.viewController代码里
//
// ViewController.swift
// Window
//
// Created by fine on 2018/8/7.
// Copyright © 2018年 fine. All rights reserved.
//
import Cocoa
import SnapKit
class ViewController: NSViewController {
@IBOutlet weak var controlContainer: NSView!
override func viewDidLoad() {
super.viewDidLoad()
// // Do any additional setup after loading the view.
//注意这里不是window实例的方法,而是NSWindow的类方法
let close = NSWindow.standardWindowButton(.closeButton, for: .borderless)
let mini = NSWindow.standardWindowButton(.miniaturizeButton, for: .borderless)
let zoom = NSWindow.standardWindowButton(.zoomButton, for: .borderless)
//将控制按钮添加到自定义容器view中
controlContainer.addSubview(close!)
controlContainer.addSubview(mini!)
controlContainer.addSubview(zoom!)
//这里使用snpkit 的来设置约束
close?.snp.makeConstraints({ (make) in
make.centerY.equalTo(controlContainer)
make.left.equalTo(controlContainer).offset(10)
})
mini?.snp.makeConstraints { (make) in
make.centerY.equalTo(controlContainer)
make.left.equalTo(close!).offset(20)
}
zoom?.snp.makeConstraints({ (make) in
make.centerY.equalTo(controlContainer)
make.left.equalTo(mini!).offset(20)
})
//设置回调事件
mini?.action = #selector(min)
zoom?.action = #selector(click(_:))
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction @objc func click(_ sender: Any) {
self.view.window?.toggleFullScreen(self);
//这里要隐藏titlebar自带的控制按钮(该控制在全屏后 鼠标置顶会出现,所以要隐藏实现和微信一的效果)
self.view.window?.standardWindowButton(.zoomButton)?.superview?.subviews.forEach({ (itemView) in
itemView.isHidden = true;
})
}
@objc func min(){
self.view.window?.performMiniaturize(self)
}
}