Reputation: 7185
In IB this can be done easily by checking the 'Resize' checkbox on or off. My problem is I want my main NSWindow to not be resizable, until a button is clicked, and then i want it to be resizable.
I've scoured the Internet but can't find anything? Can a window not be made to be resizable or not programmatically?
Thanks in advance everyone!
Upvotes: 18
Views: 15763
Reputation: 1315
I am new to macOS development. None of the above solutions worked for me (Swift 4.2). I also didn't learn that much (copy/paste doesn't help with that).
I have created this NSWindow subclass. I use it in Interface builder.
class MainDocumentChooserW: NSWindow {
// NOTE: This method is called when the Window is used via Interface builder.
// Setting the styleMask like this will override the IB settings.
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag)
styleMask = [.miniaturizable, .titled, .closable]
}
}
Tested on macOS: High Sierra 10.13.6 (17G5019).
Upvotes: 0
Reputation: 90691
Since 10.6, you can change the style mask of a window using -[NSWindow setStyleMask:]
. So, you'd do something like this:
In Objective-C
To make it resizable:
window.styleMask |= NSWindowStyleMaskResizable;
To make it non-resizable:
window.styleMask &= ~NSWindowStyleMaskResizable;
In Swift
To make it resizable:
mainWindow.styleMask = mainWindow.styleMask | NSWindowStyleMaskResizable
To make it non-resizable:
mainWindow.styleMask = mainWindow.styleMask & ~NSWindowStyleMaskResizable
Upvotes: 53
Reputation: 48205
In Swift 3,
if enabled {
window.styleMask.update(with: .resizable)
} else {
window.styleMask.remove(.resizable)
}
Upvotes: 4
Reputation: 8843
The Swift 3 solution to this issue is to use the OptionSet
class described at:
https://developer.apple.com/reference/swift/optionset
To replace the set of flags, you now do something like:
myWindow.styleMask = [ .resizable, .titled, .closable ]
To add a flag, do something like:
myWindow.styleMask.insert( [ .miniaturizable, .fullscreen ] )
To remove a flag, something like:
myWindow.styleMask.remove( [ .resizable ] )
Upvotes: 10
Reputation: 5981
In Xcode 8 / Swift 3, try something like:
// e.g., on a view controller’s viewDidAppear() method:
if let styleMask = view.window?.styleMask
{
view.window!.styleMask = NSWindowStyleMask(rawValue: styleMask.rawValue | NSWindowStyleMask.resizable.rawValue)
}
Upvotes: 1
Reputation: 96393
You can't change the style mask of a window after creating it, but you can set the window's minimum and maximum frame size to the same size. Do that after you and your resizable window awake from nib, and then change the maximum and optionally the minimum size back when the user clicks the button.
Upvotes: 4