根据变量swift调整窗口大小

时间:2015-03-23 07:36:19

标签: macos cocoa swift resize window

我有一个NSViewController和一个变量num。我想根据该变量动态地改变窗口的大小。有没有办法在swift中做到这一点?

3 个答案:

答案 0 :(得分:7)

假设您的窗口有一个名为“window”的IBOutlet,您的动态编号名为“myDynamicNumber”:

func resize() {
    var windowFrame = window.frame
    let oldWidth = windowFrame.size.width
    let oldHeight = windowFrame.size.height
    let toAdd = CGFloat(myDynamicNumber)
    let newWidth = oldWidth + toAdd
    let newHeight = oldHeight + toAdd
    windowFrame.size = NSMakeSize(newWidth, newHeight)
    window.setFrame(windowFrame, display: true)
}

答案 1 :(得分:4)

Swift 3 中调整窗口大小,使用setFrame。

ViewController的一个例子:

func resizeWin(size:(CGFloat,CGFloat)){

    self.view.window?.setFrame(NSRect(x:0,y:0,width:size.0,height:size.1), display: true)

}

答案 2 :(得分:0)

我需要切换查看文本视图,因此我将窗口覆盖了一个不可见的视图 - hideRect只是文本视图的缩写;通过这种方式,我可以调整大小(hideRect)并稍后恢复到原始大小 - origRect。在viewDidLoad()处捕获隐藏和原始rect。 Swift 3 / Xcode 8.3.3

// class global contants
let kTitleUtility =     16
let kTitleNormal =      22

@IBOutlet var hideView: NSView!
var hideRect: NSRect?
var origRect: NSRect?

@IBAction func toggleContent(_ sender: Any) {
    // Toggle content visibility
    if let window = self.view.window {
        let oldSize = window.contentView?.bounds.size
        var frame = window.frame
        if toggleButton.state == NSOffState {

            frame.origin.y += ((oldSize?.height)! - (hideRect?.size.height)!)
            window.setFrameOrigin(frame.origin)
            window.setContentSize((hideRect?.size)!)

            window.showsResizeIndicator = false
            window.minSize = NSMakeSize((hideRect?.size.width)!,(hideRect?.size.height)!+CGFloat(kTitleNormal))
            creditScroll.isHidden = true
        }
        else
        {
            let hugeSize = NSMakeSize(CGFloat(Float.greatestFiniteMagnitude), CGFloat(Float.greatestFiniteMagnitude))

            frame.origin.y += ((oldSize?.height)! - (origRect?.size.height)!)
            window.setFrameOrigin(frame.origin)
            window.setContentSize((origRect?.size)!)

            window.showsResizeIndicator = true
            window.minSize = NSMakeSize((origRect?.size.width)!,(origRect?.size.height)!+CGFloat(kTitleNormal))
            window.maxSize = hugeSize
            creditScroll.isHidden = false
        }
    }
}

这也保留了寡妇的视觉起源和最小化。