Archive for June, 2006

Version Update

Just a quick note to mention that tonight I updated the blog here to WordPress 2.0.3, as well as installed a LightBox plugin for the images (and customized it just a little, because I’m picky like that). Also, the forum was updated to phpBB 2.0.21. So yeah, all up to date. more CSS and other visual changes to come soon.

NSTableView Contextual Menu

Through some futzing around tonight, I was able to get a contextual menu for my NSTableView, that will change depending on if the user right-clicks a row of data or the nothingness beneath the data. Basically, it’s as simple as subclassing NSTableView, creating two IBOutlets for each of the NSMenus, and adding the following code:

- (NSMenu *)menuForEvent:(NSEvent *)theEvent
    int row = [self rowAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];

    if( row != -1 ) {
        [self selectRow:row byExtendingSelection:NO];
        return contextualMenuWithSelection;
    } else {
        [self deselectAll:nil];
        return contextualMenuWithNoSelection;

NSTableView Dragging

I wanted to be able to Drag and Drop the rows of some of my NSTableViews, especially for being able to rearrange the courses in Assignment Planner. This seemed like a pretty resonable task, but a lot of the Documentation for it is fairly complicated. However, I stumbled across this lovely blog post by Corbin, which had these few easy steps (slightly edited here)…

Declare your custom pasteboard format:

#define BasicTableViewDragAndDropDataType @"BasicTableViewDragAndDropDataType"

In awakeFromNib you must register for the drag types you want to receive (you could have others here):

- (void)awakeFromNib
    [tableView registerForDraggedTypes:[NSArray arrayWithObjects:BasicTableViewDragAndDropDataType, nil]];

Then, you must implement writeRowsWithIndexes to add your data to the pasteboard:

- (BOOL)tableView:(NSTableView *)tv
    writeRowsWithIndexes:(NSIndexSet *)rowIndexes
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
    [pboard declareTypes:[NSArray arrayWithObject:BasicTableViewDragAndDropDataType] owner:self];
    [pboard setData:data forType:BasicTableViewDragAndDropDataType];
    return YES;

Next you will validate the drop:

- (NSDragOperation)tableView:(NSTableView*)tv
    validateDrop:(id )info
    return NSDragOperationEvery;

Finally, you must have a method that accepts the drop. Here you could access the BasicTableViewDragAndDropDataType and look at the rows that were dragged.

- (BOOL)tableView:(NSTableView*)tv
    acceptDrop:(id )info
    return YES;

And that is it! It is pretty easy!

Very easy indeed! Just one note, I personally like to have the validate drop return op == NSTableViewDropAbove;, which will only allow an item to be dropped when it is in between two other items and it doesn’t allow for nesting drops.

:: RSS Feed :: Archive :: Categories :: Admin