I want to add a NSWindow the simple code is :
NSWindow* myWindow;
myWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
styleMask:NSTitledWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[myWindow makeKeyAndOrderFront:nil];
And the window appears for a second then disappears. What's wrong?
Thanks for your answer.
You are not retaining the window.
Define NSWindow* myWindow;
in .h as a property.
In .h
@property (strong)NSWindow* myWindow;
In .m
- (IBAction)button:(id)sender {
if (self.myWindow==nil){
self.myWindow= [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
styleMask:NSTitledWindowMask
backing:NSBackingStoreBuffered
defer:NO];
}
[self.myWindow makeKeyAndOrderFront:NSApp];
}
EDIT:
If you want multiple windows to open from same button. Create an array
In .h
@property(strong) NSMutableArray *myWindowArray;
In .m
- (IBAction)button:(id)sender {
self.myWindow= [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
styleMask:NSTitledWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[self.myWindowArray addObject:self.myWindow];
for (NSWindow *win in self.myWindowArray) {
[win makeKeyAndOrderFront:NSApp];
}
}
EDIT 2:
Find the application here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With