这篇文章将会教你如何在NSSplitView窗口大小变化时固定某一个子视图的大小
This is an article about how to fix the size of one of the subviews while a NSSplitView is stretched to resize.
NSSplitView 是 macOS 开发中最常用的组件之一,它用来管理和分割两个或多个子视图,并形成水平或者垂直布局
NSSplitView is one of the most commonly used components in macOS development. It is used to manage and split two or more subviews and form a horizontal or vertical layout.
首先,文章所述方法仅适用于自动布局
First of all, the method described in the article is only applicable to Auto Layout
让我们一起来看看NSSplitView在自动布局下的表现
Let's take a look at the performance of NSSplitView in automatic layout
创建一个工程,在 storyboard 中编辑页面如下
Create a project and edit the page in the storyboard like the following
运行应用并伸缩窗口,两个子视图会同时缩放,接下来,在左边的视图上添加固定宽度约束,为了直观起见,我们分别在两个子视图中添加居中的标签
Run the application and shrink the window, both subviews will resize at the same time. Next, add fixed width constraints on the left view. For the sake of clarity, we add centered labels in the two subviews.
运行应用并伸缩窗口,左侧视图大小不变,右侧视图自适应改变,这显然不是我们要的效果
Run the application and shrink the window, the left view size does not change, the right view will adaptive it's size, which is obviously not the effect we want
我们想要的效果是,左侧视图宽度限定在一个范围内,只是在伸缩外层窗口时保持左侧视图宽度不变,就像微信客户端那样。修改左侧视图的约束,让其宽度限定在200到250之间
The effect we want is that the width of the left view is confined to a range, but the width of the left view remains constant when the outer window is stretched, just like the WeChat client. Modify the constraints of the left view so that its width is limited to 200 to 250
运行应用并伸缩窗口,左侧视图的宽度受到了约束,但是外层窗口伸缩时,其宽度仍然会改变,让我们回到代码中来完成最后一步
Run the application and shrink the window, the width of the left view is constrained, but when the outer window scales, its width still changes, let's go back to the code to complete the last step
将 storyboard 中的 NSSplitView 连接到 ViewController.swift 中
Connect the NSSplitView in storyboard to ViewController.swift
现在把注意力转移到 NSNotification 和 NSSplitView,当窗口伸缩时,我们能捕捉到两个通知 NSWindow.willStartLiveResizeNotification 和 NSWindow.didResizeNotification,在窗口伸缩之前记录左侧视图的宽度,在窗口伸缩之后使用 NSSplitView 的 setPosition:ofDividerAt: 方法重新布局子视图,任务完成
Now turn our attention to NSNotification and NSSplitView. When the window is stretched, we can capture two notifications, NSWindow.willStartLiveResizeNotification and NSWindow.didResizeNotification. Record the width of the left view before the window is scaled, and instance method setPosition:ofDividerAt: of NSSplitView after the window is stretched to Re-layout Subviews, Done
import Cocoa
class ViewController: NSViewController {
@IBOutlet var splitView: NSSplitView!
private var leftViewPreviousWidth: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(windowWillResize(notification:)),
name: NSWindow.willStartLiveResizeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(windowDidResize(notification:)),
name: NSWindow.didResizeNotification, object: nil)
}
@objc func windowWillResize(notification: Notification) {
if notification.object as? NSWindow != splitView.window {
return
}
leftViewPreviousWidth = splitView.arrangedSubviews.first?.frame.width ?? 0
}
@objc func windowDidResize(notification: Notification) {
if notification.object as? NSWindow != splitView.window {
return
}
splitView.setPosition(leftViewPreviousWidth, ofDividerAt: 0)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
垂直布局的 NSSplitView 实现方式类似,这个方法很简单但是使用起来很麻烦,接下来我们把这个功能封装起来,简单起见,我们只支持最边上的视图固定
Similar implementation for NSSplitView in vertical layout. It's quite simple but not convenient to use, let's make encapsulation, For simplicity, it only supports side views to fix
import Cocoa
extension NSSplitView {
enum FixableSide {
case begin
case end
}
class Fixable: NSObject {
weak private var splitView: NSSplitView?
var side: FixableSide = .begin
var previousSize: CGFloat = 0
init(splitView: NSSplitView) {
super.init()
self.splitView = splitView
DispatchQueue.main.async {
NotificationCenter.default.addObserver(self, selector: #selector(self.windowWillResize(notification:)),
name: NSWindow.willStartLiveResizeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.windowDidResize(notification:)),
name: NSWindow.didResizeNotification, object: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
var fixedView: NSView? {
if side == .begin {
return splitView?.arrangedSubviews.first
} else {
return splitView?.arrangedSubviews.last
}
}
var recordedSize: CGFloat {
if splitView?.isVertical == true {
return fixedView?.frame.width ?? 0
}
return fixedView?.frame.height ?? 0
}
func adjustSplitViewPosition() {
if splitView == nil {
return
}
if side == .begin {
splitView!.setPosition(previousSize, ofDividerAt: 0)
} else {
if splitView!.isVertical {
splitView!.setPosition(splitView!.frame.width - previousSize, ofDividerAt: splitView!.arrangedSubviews.count - 2)
} else {
splitView!.setPosition(splitView!.frame.height - previousSize, ofDividerAt: splitView!.arrangedSubviews.count - 2)
}
}
}
@objc func windowWillResize(notification: Notification) {
if notification.object as? NSWindow != splitView?.window {
return
}
previousSize = recordedSize
}
@objc func windowDidResize(notification: Notification) {
if notification.object as? NSWindow != splitView?.window {
return
}
adjustSplitViewPosition()
}
}
private static var fixableVariableKey: UInt = 666666
private var fixable: Fixable? {
get {
return objc_getAssociatedObject(self, &NSSplitView.fixableVariableKey) as? Fixable
}
set {
objc_setAssociatedObject(self, &NSSplitView.fixableVariableKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var fixableSide: FixableSide? {
get {
return fixable?.side
}
set {
if newValue == nil {
fixable = nil
} else {
if let fixable = self.fixable {
fixable.side = newValue!
} else {
let fixable = Fixable.init(splitView: self)
fixable.side = newValue!
self.fixable = fixable
}
}
}
}
}
现在我们只需要一行代码就能实现
Now we only need a single line of code to implement
import Cocoa
class ViewController: NSViewController {
@IBOutlet var splitView: NSSplitView!
override func viewDidLoad() {
super.viewDidLoad()
//set it to .end to change it's fixableSide
//set it to nil to close it's fixableSide
splitView.fixableSide = .begin
}
}