I'm new to Cocoa/Objective-c
so please bear with me on this.
I'm trying to create a simple program that has a TableView
on the left of the window and a CustomView on the right. The TableView has 3 columns: (NSString) name, (NSInteger) x, (NSInteger) y.
The x and y values are randomly generated between 0 and 100 whenever a new row is added. I have a simple Star class to hold these three attributes. The TableView seems to be working just fine.
On the right, I have a CustomView
where I want to load an image whenever a new row is added to the tableview
at the x,y for that entry.
I created this "addStar"
method in the CustomView
class, which is an NSView
. Then, in my TableViewController class, I'm trying to call the "addStar"
method in my "add" method that adds a new row.
When I launch the program, I'm able to add items to the TableView
, but nothing shows up in the CustomView
. Any ideas of where I'm going wrong here?
CustomView.m
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
NSBezierPath* path = [NSBezierPath bezierPathWithRect:self.bounds];
[[NSColor whiteColor] setFill];
[path fill];
}
- (void)addStar:(float)x and:(float)y
{
NSRect rect = NSMakeRect(x, y, 35, 35);
imageView = [[NSImageView alloc] initWithFrame:rect];
[imageView setImageScaling:NSScaleNone];
[imageView setImage:[NSImage imageNamed:@"star.png"]];
[self addSubview:imageView];
}
@end
TableViewController.m
#import "TableViewController.h"
#import "CustomView.h"
#import "Star.h"
@implementation TableViewController
- (id)init
{
self = [super init];
if (self) {
list = [[NSMutableArray alloc] init];
}
return self;
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [list count];
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
Star *s = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [s valueForKey:identifier];
}
- (void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
Star *s = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[s setValue:object forKey:identifier];
}
// Add row to the tableview
- (IBAction)add:(id)sender {
Star *star = [[Star alloc] init];
[list addObject:star];
[tableView reloadData];
// add star to the custom view
CustomView* cv = [[CustomView alloc] init];
[cv addStar:(float)[star xCoordinate] and:(float)[star yCoordinate]];
[star release];
}
- (IBAction)remove:(id)sender {
NSInteger row = [tableView selectedRow];
[tableView abortEditing];
if (row != -1)
[list removeObjectAtIndex:row];
[tableView reloadData];
}
- (void)dealloc
{
[list release];
[super dealloc];
}
@end