NSWindow Disappears - objective-c

I have this code set to run on my app launch:
NSRect rect = NSMakeRect(0, 0, 200, 50); //The location of the window
NSWindow *win = [[NSWindow alloc] initWithContentRect:rect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
[win setOpaque:NO];
[win setLevel:NSFloatingWindowLevel];
//[win setBackgroundColor:[NSColor clearColor]];
//or
NSView *myView = [[NSView alloc] initWithFrame: NSMakeRect(0, 0, 200, 50)];
NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(10, 5, 180, 40)];
[myView addSubview: myButton];
[win setHidesOnDeactivate:NO];
[win setContentView: myView];
[win orderFront: nil];
It works as expected (displays a button in the bottom left hand corner of the screen) for about a second, then it disappears. Why is it disappearing? Memory management, or something else, and how do I fix it?

First, it is extremely odd to be building user interface without simply using Interface Builder. Can be done and there are a handful of reasons to do so, but they are pretty few and far between.
Next, that code, by itself, isn't enough to say what has gone wrong. Creating a UI programmatically begs a whole series of questions; gc or not? ... how is your run loop configured? ... do you have a properly configured app wrapper?
As Abizem said, the most obvious guess would be that you have GC enabled and you haven't rooted the window in some global variable somewhere, directly or indirectly. It "just works" in a standard Cocoa application because NSWindow instances are rooted via the Cocoa application infrastructure (the Windows menu, specifically).

Are you working with Garbage Collection?
Do you have an iVar that is holding on to win? It could be that it is being garbage collected out from under you.

Related

View not updating when it's properties change in custom delegate

I have an ACPDownloadView instance of AppDelegate. It's showing downloading progress. When I update it's progress value in my view controller, it works fine.
appdelegate.downloadVew=[[ACPDownloadView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
appdelegate.downloadVew.backgroundColor=[UIColor clearColor];
progressBtn= [[UIBarButtonItem alloc] initWithCustomView:appdelegate.downloadVew];
ACPIndeterminateGoogleLayer * layer = [ACPIndeterminateGoogleLayer new];
[layer updateColor:[UIColor blueColor]];
[appdelegate.downloadVew setIndeterminateLayer:layer];
[appdelegate.downloadVew setIndicatorStatus:ACPDownloadStatusRunning];
[appdelegate.downloadVew setProgress:0.0 animated:NO];
Now, I have a delegate method which called when progress updated.
-(void)progressAddChannel:(NSProgress *)uploadProgress{
float prog=uploadProgress.fractionCompleted;
[appdelegate.downloadVew setProgress:prog animated:YES];
[appdelegate.downloadVew layoutIfNeeded];
NSLog(#"%f",prog);
}
This code executes and show correct value of progress. But that progress is not animating on appdelegate.downloadVew. Do anyone know about this behavior?
Since you are making UI changes make sure your code runs on the main thread.

addSubview not showing up in NSView Objective C Cocoa

When I addSubview: nothing shows up. I set text and color to see it. Also if I manually add the view to the custom view in the UI bulder in xcode it shows up just fine with the text and color.
.m file
- (void)displayString:(NSString *)title {
NSRect frame = NSMakeRect(10, 10, 200, 17);
NSTextfield *newfield = [[NSTextField alloc] initWithFrame:frame];
[newfield setBezeled:NO];
[newfield setDrawsBackground:NO];
[newfield setEditable:NO];
[newfield setSelectable:NO];
[newfield setStringValue:title];
[newfield setTextColor:[NSColor blueColor]];
[test addSubview:newfield];
if([test.subviews containsObject:newfield]){
NSLog(#"view there"); // i get this message
}
if([newfield isHidden]){
NSLog(#"view hidden"); //i dont get this message
}
NSLog(#"view set");
}
test is a NSView (Custom view is what xcode calls it) that I have properly linked in.
So when I create the text field and add it to the NSView manually and then run that same code by adding text and color all works fine, this issue arrises when I try programmatically setting the view. Also I made sure it wasn't my creating of the view, as I have tried creating the view in the builder and not placing it in the NSView and then trying addSubview: but that also does not work. Let me know if you need more code.
DEVELOPMENT:
If the nsview (custom view) has an element already in it (manually added and can be anything) and I add the text field it works (I get both views in the nsview)? The subview is tested for and there, just cant see it.
You have to call initWithFrame: instead of just init
- (void)displayString:(NSString *)title {
NSRect frame = NSMakeRect(10, 10, 200, 200);
NSTextField *newfield = [[NSTextField alloc] initWithFrame:frame];
[newfield setStringValue:title];
[newfield setTextColor:[NSColor blueColor]];
[test addSubview:newfield];
NSLog(#"view set");
}
What type of view is test? Also you need to do a:
newfield.frame = CGRectMake(x,y,width,height)
in order to specify the look of the view
Turns out I set the view too early. I was under the impression that whatever you do to the view after its been set will be reflected on the view, but that seemed to be the issue. After altering the view to be exactly they way I want then set the view of the NSStatuditem.
so I get
[newfield setStringValue:title];
[newfield setTextColor:[NSColor blueColor]];
[test addSubview:newfield];
[statusItem setView:test];//this is the key, setting it after he changes.

How to add an NSView to NSWindow in a Cocoa app?

Since the template of an OS X app in Xcode seems to be similar to an empty app template, the following is used to add a view and a button (trying not to use Interface builder for now):
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(100, 100, 100, 100)];
view.layer.backgroundColor = [[NSColor yellowColor] CGColor];
[self.window.contentView addSubview:view];
NSRect frame = NSMakeRect(10, 40, 90, 40);
NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];
pushButton.bezelStyle = NSRoundedBezelStyle;
[self.window.contentView addSubview:pushButton];
NSLog(#"subviews are %#", [self.window.contentView subviews]);
}
Similar code on iOS should have produced a yellow box and a button, but the code above only produce a button, but the view won't show. Is there something wrong with the code above, and how to make it show the view with a yellow background?
Use setWantsLayer: method of NSView class.
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(100, 100, 100, 100)];
[view setWantsLayer:YES];
view.layer.backgroundColor = [[NSColor yellowColor] CGColor];
[self.window.contentView addSubview:view];
NSRect frame = NSMakeRect(10, 40, 90, 40);
NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];
pushButton.bezelStyle = NSRoundedBezelStyle;
[self.window.contentView addSubview:pushButton];
NSLog(#"subviews are %#", [self.window.contentView subviews]);
To expand on the suggestion by Kevin Ballard, the classic way to do this is to subclass NSView and override the -drawRect: method. NSRectFill is a very convenient function for filling a rectangle without having to create a bezier path:
- (void)drawRect:(NSRect)rect
{
[[NSColor yellowColor] set];
NSRectFill(rect);
}
NSViews in Cocoa are, by default, not layer-backed. I suspect that if you type
NSLog(#"%#", view.layer);
you will see that it is nil.
In iOS, all views have layers. But on OS X, views don't have layers. In addition, there's 2 "modes" of layer-backed views on OS X. There's what's called a "layer-backed views" and a "layer-hosting view". A layer-backed view uses a CoreAnimation layer to cache drawn data, but you are not allowed to interact with the layer in any way. A layer-hosting view uses a CALayer that you explicitly provide, and you may mess with that layer all you want. However, with a layer-hosting view you may not add any subviews, or use the built-in NSView drawing mechanism. A layer-hosting view must only be used as the root of a CoreAnimation layer hierarchy.
Given all this, you should probably avoid using CoreAnimation at all for your view.
It's possible that an NSBox will do what you want. You can certainly set a fill color there, turn off the border, and set the style to custom. I'm just not 100% certain it will draw as a simple filled rectangle of color. Alternatively you can define your own NSView subclass that draws a color in -drawRect:.

Programmatically create NSWindow with specific size fails

I'm trying to programmatically create a borderless NSWindow close to the mouse cursor and with the size of the image it should display. However I always get a much larger window (each side is about three times the size it should be)! I double-checked that my imageObj has the correct size and that all the NSSize and NSRect structures are created with correct values. The commented-out line doesn't work either (however which would be correct?)
I already searched through this site but I couldn't find any similar issue... What am I doing wrong?
Here is my code:
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"os_unknown" ofType:#"icns"];
NSImage* imageObj = [[NSImage alloc] initWithContentsOfFile:imageName];
[view setImage:imageObj];
NSSize s = [imageObj size];
NSPoint p = [NSEvent mouseLocation];
NSRect r = [NSWindow frameRectForContentRect:NSMakeRect(p.x, p.y, s.width, s.height)
styleMask:NSBorderlessWindowMask];
//NSRect r = {p, s};
if (win) [win release];
win = [[NSWindow alloc] initWithContentRect:r
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:false];
[win setLevel:kCGUtilityWindowLevel];
[view setBounds:NSMakeRect(0, 0, s.width, s.height)];
[[win contentView] addSubview:view];
[win orderFront:sender];
Here *win is an NSWindow and *view is an NSImageView. Both are declared on top of my source file.
I'm running Snow Leopard so any strictly >10.6.8 code won't work (already tried something).
Thank you in advance for any help.
Solved! The NSImageView *view was created in Interface Builder. The size I got was the size set in there, no matter what code I used to resize it. By creating the NSImageView programmatically everything works great!
Special thanks to rdelmar who made me think and get the solution!

UIView size is not as expected to be

I can't figure out why that view takes the entire screen.
In AppDelegate file
...
self.viewController = [[[ViewController alloc]init]autorelease];
[self.window setRootViewController:self.viewController];
self.window.backgroundColor = [UIColor whiteColor];
..
In ViewController.m
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)];
[view setBackgroundColor:[UIColor greenColor]];
self.view = view;
When I run the app the screen is entirely green instead of having just a square in green.
What is wrong here ?
The erroneous line is here:
self.view = view;
When you set a view of a UIViewController that is the root controller, it is guaranteed to fill the screen. Instead, add it as a subview:
[self.view addSubview:view];
And you should be fine.
The view controller automatically manages the size of its root view (self.view), so even if you initialize it with a smaller size it will later get resized to fill the screen. This resizing conveniently also happens when the interface orientation changes (see the answer this question).
As suggested by Richard's answer, you can add your green view as a subview to the controller's root view. The crash you get is probably because the root view does not exist yet when you try to access it. Try the following:
- (void) loadView
{
[super loadView]; // creates the root view
UIView* subView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 30, 30)];
[subView setBackgroundColor:[UIColor greenColor]];
// because you don't set any autoresizingMask, subView will stay the same size
[self.view addSubview:subView];
}