NSSplitView resize时固定某一个子视图的方法

这篇文章将会教你如何在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

picture_0

运行应用并伸缩窗口,两个子视图会同时缩放,接下来,在左边的视图上添加固定宽度约束,为了直观起见,我们分别在两个子视图中添加居中的标签
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.

picture_1

运行应用并伸缩窗口,左侧视图大小不变,右侧视图自适应改变,这显然不是我们要的效果
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

picture_2

运行应用并伸缩窗口,左侧视图的宽度受到了约束,但是外层窗口伸缩时,其宽度仍然会改变,让我们回到代码中来完成最后一步
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

picture_3

将 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
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,126评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,254评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,445评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,185评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,178评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,970评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,276评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,927评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,400评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,883评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,997评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,646评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,213评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,204评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,423评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,423评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,722评论 2 345

推荐阅读更多精彩内容