Cocoa: NSView not drawing rect - cocoa

I have a class called ServerImage (sub of NSView) which I am calling from my AppController but for some reason it won't draw to the screen. I have other views which I am able to draw and add images to but for some reason not this one. I'm sure I am missing something in my code but am just not seeing it. Here's the relevant code from AppController:
//loop through masterServerDict and get server status
NSMutableString* key;
for(key in masterServerDict) {
ServerImage* newImage = [[ServerImage alloc] initWithFrame:NSMakeRect(200.0, 0.0, 48.0, 48.0)];
[newImage setServerName:key];
[[[NSApp mainWindow] contentView] addSubview:newImage];
[newImage setNeedsDisplay:YES];
}
masterServerDict is a mutable dictionary, the key is the name of a server, the object is an array, it holds the smb and afp paths to the server and whether it is mounted or not.
Here is ServerImage.h
#import <Cocoa/Cocoa.h>
#interface ServerImage : NSView {
NSString * serverName;
}
- (void) setServerName : (NSString* ) s;
#end
and ServerImage.m
#import "ServerImage.h"
#implementation ServerImage
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
NSLog(#"%f", self.frame.origin.x);
}
return self;
}
- (void)drawRect:(NSRect)rect {
NSLog(#"drawrect");
[[NSColor redColor] set];
NSRectFill(rect);
}
- (void) setServerName : (NSString* ) s {
NSLog(#"method");
serverName = s;
}
I can get the init and setServerName methods to log but not drawRect...

Check if [[NSApp mainWindow] contentView] is non-nil. Also check if it refers to the right window and that the coordinate is good (visible).

Related

Cocoa: NSToolBar with Custom Views. Animation issues

So I got a Window:
Window.xib
I got a WindowController too:
WindowController.h reads:
#import <Cocoa/Cocoa.h>
#interface MainWindowController : NSWindowController
{
IBOutlet NSView *firstView;
IBOutlet NSView *secondView;
IBOutlet NSView *thirdView;
int currentViewTag;
}
-(IBAction)switchView:(id)sender;
#end
And the WindowController.m reads:
#import "MainWindowController.h"
#interface MainWindowController ()
#end
#implementation MainWindowController
-(id)init
{
self = [super initWithWindowNibName:#"MainWindow"];
if (self){
// Initialization code here
}
return self;
}
//- (void)windowDidLoad {
// [super windowDidLoad];
//
// // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
//}
#pragma mark - Custom view drawing
-(NSRect)newFrameForNewContentView:(NSView *)view
{
NSWindow *window = [self window];
NSRect newFrameRect = [window frameRectForContentRect:[view frame]];
NSRect oldFrameRect = [window frame];
NSSize newSize = newFrameRect.size;
NSSize oldSize = oldFrameRect.size;
NSRect frame = [window frame];
frame.size = newSize;
frame.origin.y -= (newSize.height - oldSize.height);
return frame;
}
-(NSView *)viewForTag:(int)tag{
NSView *view = nil;
if (tag == 0) {
view = firstView;
} else if (tag == 1) {
view = secondView;
} else {
view = thirdView;
}
return view;
}
-(BOOL) validateToolbarItem:(NSToolbarItem *)item
{
if ([item tag] == currentViewTag) return NO;
else return YES;
}
-(void)awakeFromNib
{
[[self window] setContentSize:[firstView frame].size];
[[[self window] contentView]addSubview:firstView];
[[[self window] contentView]setWantsLayer:YES];
}
-(IBAction)switchView:(id)sender
{
int tag = [sender tag];
NSView *view = [self viewForTag:tag];
NSView *previousView = [self viewForTag:currentViewTag];
currentViewTag = tag;
NSRect newFrame = [self newFrameForNewContentView:view];
[NSAnimationContext beginGrouping];
if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask)
[[NSAnimationContext currentContext] setDuration:1.0];
[[[[self window]contentView]animator]replaceSubview:previousView with:view];
[[[self window]animator]setFrame:newFrame display:YES];
[NSAnimationContext endGrouping];
}
#end
The problem I have is that when i switch tabs in my app, the custom view (and there are three of different sizes) draw differently each time. Look at the screenshots, all of the numbers should be centre aligned but they are sometimes and others not. Can anyone see what my error is please?
I will also add that all of the actions have been correctly configured + the code works perfectly if the custom view size is the same all the time.
The view that works
The view that almost works
Again pointing out that in my .xib all of the numbers are aligned to 0x and 0y axis.
Appdelegate.h
#import <Cocoa/Cocoa.h>
#class MainWindowController;
#interface AppDelegate : NSObject <NSApplicationDelegate> {
MainWindowController *mainWindowController;
}
#end
Appdelegate.m
#interface AppDelegate ()
#property (nonatomic) IBOutlet NSWindow *window;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
-(void)awakeFromNib
{
if(!mainWindowController){
mainWindowController = [[MainWindowController alloc]init];
}
[mainWindowController showWindow:nil];
}
#end
In Interface Builder, make sure to disable the "autoresizes subviews" checkbox of the default view of your window

Custom NSButtonCell, drawBezelWithFrame not called

I'm trying to figure out how to custom draw Buttons in Cocoa/OSX. Since my view is custom drawn I will not use IB and want to do it all in code. I created a subclass of NSButtonCell and a subclass of NSButton. In the Subclass of NSButtonCell I override the Method drawBezelWithFrame:inView: and in the initWithFrame Method of my subclassed NSButton I use setCell to set my CustomCell in the Button. However, drawBezelWithFrame gets not called and I don't understand why. Can someone point out what I've done wrong or what I miss here?
Subclass of NSButtonCell:
#import "TWIButtonCell.h"
#implementation TWIButtonCell
-(void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView
{
//// General Declarations
[[NSGraphicsContext currentContext] saveGraphicsState];
//// Color Declarations
NSColor* fillColor = [NSColor colorWithCalibratedRed: 0 green: 0.59 blue: 0.886 alpha: 1];
//// Rectangle Drawing
NSBezierPath* rectanglePath = [NSBezierPath bezierPathWithRect: NSMakeRect(8.5, 7.5, 85, 25)];
[fillColor setFill];
[rectanglePath fill];
[NSGraphicsContext restoreGraphicsState];
}
#end
Subclass of NSButton:
#import "TWIButton.h"
#import "TWIButtonCell.h"
#implementation TWIButton
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
TWIButtonCell *cell = [[TWIButtonCell alloc]init];
[self setCell:cell];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
}
#end
Usage:
- (void)addSendButton:(NSRect)btnSendRectRect
{
TWIButton *sendButton = [[TWIButton alloc] initWithFrame:btnSendRectRect];
[self addSubview:sendButton];
[sendButton setTitle:#"Send"];
[sendButton setTarget:self];
[sendButton setAction:#selector(send:)];
}
Following are the things seems to be missing out from your code.
You are not calling the [super drawRect:dirtyRect]
You are not overriding + (Class)cellClass in the Class(TWIButton) which is derived from NSButton.
Below is the code after changes:
#implementation TWIButton
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
TWIButtonCell *cell = [[TWIButtonCell alloc]init];
[self setCell:cell];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
//Changes Added!!!
[super drawRect:dirtyRect];
}
//Changes Added!!!!
+ (Class)cellClass
{
return [TWIButtonCell class];
}
#end
Now keep the break point at drawBezelWithFrame and check it will get called.
One might forgo the NSButton subclass, since it looks like you are ONLY using it to instantiate the Cell type within the initializer.
Simply
NSButton *button ...
[button setCell: [[TWIButtonCell alloc] init] autorelease]];
btw. you will probably have a leak in the previous examples since you init and then call setCell that likely has its own retain.

Equivalent of clipToBounds for Mac (NSView's layer)

I have a class "GlobalView" which extends NSView and has two subviews GreenRectView (which extends NSView).
I use the CALayer from my GreenRectView in order to be able to rotate (with setAffineTransform:) my view around a point other than the default bottom-left point. Thus I used "setAnchorPoint". Everything works well except that when my green rect is rotated , it is not draw outside the bounds of its view. In iOS it is possible to use clipToBounds:NO to accept that drawing is display outside bounds but in Mac it doesn't work with masksToBounds... How can I rotate my greenrect and display it entirely whatever the angle of rotation.
See picture :
And here is the code :
#implementation GlobalView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
g = [[GreenRectView alloc]initWithPoint:NSMakePoint(200, 200)];
[self addSubview:g];
g = [[GreenRectView alloc]initWithPoint:NSMakePoint(100, 400)];
[self addSubview:g];
}
return self;
}
#import <Quartz/Quartz.h>
#include <ApplicationServices/ApplicationServices.h>
#implementation GreenRectView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setWantsLayer:YES];
layer = [self layer];
[self setLayer:layer];
[layer setAnchorPoint:NSMakePoint(0.0,0.5)];
[layer setMasksToBounds:NO];
[menuLayer addSublayer:layer];
}
return self;
}
- (id)initWithPoint:(CGPoint)p {
return [self initWithFrame:NSMakeRect(p.x, p.y, 120, 100)];
}
- (void)drawRect:(NSRect)dirtyRect {
[[NSColor greenColor] setFill];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSMakeRect(0,0, self.frame.size.width, self.frame.size.height) xRadius:5.5 yRadius:5.5];
[path stroke];
}

Cocoa -- getting a simple NSImageView to work

I am confused about why this code does not display any image:
In the app delegate:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSRect rect = window.frame;
rect.origin.x = 0;
rect.origin.y = 0;
BlueImageView *blueImageView = [[BlueImageView alloc]initWithFrame:rect];
window.contentView = blueImageView; // also tried [window.contentView addSubview: blueImageView];
}
BlueImageView.h:
#interface BlueImageView : NSImageView {
}
#end
BlueImageView.m:
#implementation BlueImageView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setImage: [NSImage imageNamed:#"imagefile.png"]];
NSAssert(self.image, #"");
NSLog (#"Initialized");
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
}
#end
The file imagefile.png exists. The NSAssert is not causing an exception. The NSLog is firing. But no image shows up in the window.
The drawRect: method is called to draw the view, and your implementation immediately returns. To get NSImageView to draw the image for you, call [super drawRect:dirtyRect]; in your implementation of drawRect:. If you aren't going to do any other drawing in drawRect:, just remove the method to speed up drawing.

How to display unarchived custom NSView objects

I’m learning Cocoa programming, and I’m unable to figure out how to
archive and unarchive a custom NSView subclass
I’ve made a toy application that presents a window. This window
contains an instance of my custom BackgroundView class (archived in
the xib file). Clicking anywhere in this BackgroundView creates and
displays a blue square whose origin is the click point. This square is
an instance of my Square class. All of this works as I expect.
The Square class implements the NSCoding protocol. I’ve added
dataOfType: typeName: error: and readfromData: ofType: error: methods
to the MyDocument class. As far as I can tell from log statements, the
Squares are being archived to the file, and unarchived when the file
is loaded. But I’m unable to make the squares display themselves on
the window. The Square class’s drawWithRect: method is never called,
even though I’ve called setNeedsDisplay:YES on each square.
The code is as follows:
Square.h
#import <Cocoa/Cocoa.h>
#interface Square : NSView <NSCoding> {
}
#end
Square.m
#import "Square.h"
#implementation Square
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
return self;
}
- (void)drawRect:(NSRect)rect {
[[NSColor blueColor] set];
NSBezierPath *newPath = [NSBezierPath bezierPathWithRect:[self bounds]];
[newPath fill];
}
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeRect:[self frame] forKey:#"frame"];
}
-(id)initWithCoder:(NSCoder *)coder
{
NSRect theRect = [coder decodeRectForKey:#"frame"];
self = [super initWithFrame:theRect];
return self;
}
#end
-----
BackgroundView.h
#import <Cocoa/Cocoa.h>
#interface BackgroundView : NSView {
}
#end
BackgroundView.m
#import "BackgroundView.h"
#import "Square.h"
#implementation BackgroundView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)rect {
for (Square *subview in self.subviews)
[subview setNeedsDisplay:YES];
}
-(void)mouseDown:(NSEvent *)theEvent {
NSPoint unsetClick = [theEvent locationInWindow];
NSPoint theClick = [self convertPoint:unsetClick fromView:nil];
NSRect theRect;
theRect.origin = theClick;
theRect.size.width = 100.00;
theRect.size.height = 100.00;
Square *newSquare = [[Square alloc] initWithFrame:theRect];
[self addSubview:newSquare];
[newSquare setNeedsDisplay:YES];
}
#end
------
MyDocument.h
#import <Cocoa/Cocoa.h>
#class BackgroundView;
#interface MyDocument : NSDocument
{
IBOutlet BackgroundView *theBackgroundView;
}
#end
MyDocument.m
#import "MyDocument.h"
#implementation MyDocument
- (id)init
{
self = [super init];
return self;
}
- (NSString *)windowNibName
{
return #"MyDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
[super windowControllerDidLoadNib:aController];
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
return [NSKeyedArchiver
archivedDataWithRootObject:[theBackgroundView subviews]];
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain
code:unimpErr userInfo:NULL];
}
return nil;
}
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName
error:(NSError **)outError
{
[theBackgroundView setSubviews:[NSKeyedUnarchiver
unarchiveObjectWithData:data]];
[theBackgroundView setNeedsDisplay:YES];
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain
code:unimpErr userInfo:NULL];
}
return YES;
}
#end
Since Square is a subclass of NSView, and NSView also implements NSCoding, you need to invoke super's implementation of both encodeWithCoder: and initWithCoder:.
#implementation Square
- (id)initWithFrame:(NSRect)frame
{
return [super initWithFrame:frame];
}
-(id)initWithCoder:(NSCoder *)coder
{
if ((self = [super initWithCoder:coder]))
{
NSRect theRect = [coder decodeRectForKey:#"frame"];
self = [super initWithFrame:theRect];
return self;
}
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[super encodeWithCoder:coder];
[coder encodeRect:[self frame] forKey:#"frame"];
}
- (void)drawRect:(NSRect)rect
{
[[NSColor blueColor] set];
[[NSBezierPath bezierPathWithRect:[self bounds]] fill];
}
#end
As I can see you don't add any of the initWithXXX and encodeWithXXX methods since you don't have custom member variables.
I suggest to check out Apple's Sketch Example.

Resources