Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a NSTableCellView editable

I created a View-Based NSTableView with a single column. This column is populated with a standard NSTableCellView from Interface Builder (I chose the version with image and textfield).

Now I want to make the textfield in the column editable.

My first attempt was to modify the NSTextField from Interface builder and set its behaviour as Editable. It works, indeed when I select a row and I push the enter key the field becomes editable and I can change its value. I thought I would be able to intercept this change thanks to some NSTableViewDataSource method like tableView:setObjectValue:forTableColumn:row: but this method never gets called in response of a textfield edit action.

Which is the right way to deal with editable field in a view-based NSTableView system? I suppose that the NSTableViewDataSource has something to do with it but I don't know how to get its methods called.

like image 281
MatterGoal Avatar asked Oct 06 '22 18:10

MatterGoal


2 Answers

Create a subclass of NSTableCellView. (The appropriate .h and .m files) Make the class respond to the NSTextFieldDelegate protocol. Implement the control:textShouldEndEditing: method. Make this subclass the delegate of your label control.

Here is some example code.

CategoryListCell.h

@interface CategoryListCell : NSTableCellView
@end

CategoryListCell.m

@interface CategoryListCell()<NSTextFieldDelegate>
@property (weak) IBOutlet NSTextField *categoryLabel;
@property (assign) BOOL editing;
@property (copy) NSString* category;
@end

@implementation CategoryListCell
- (BOOL)control:(NSControl*)control textShouldBeginEditing:(NSText *)fieldEditor {
   self.editing = YES;
   return YES;
}

- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor; {
   if (self.editing) {
        self.editing = NO;
        [self mergeFromSource:self.category toDestination:self.categoryLabel.stringValue];
   }
   return YES;
}

- (void)mergeFromSource:(NSString*)source toDestination:(NSString*) destination {
 // your work here
}

@end
like image 154
Aaron Bratcher Avatar answered Oct 10 '22 03:10

Aaron Bratcher


Sounds like you need to subclass the NSView that's in the NSTableView cell and make the subclassed view a delegate of the textfield. Your view will then get text change notifications via the NSTextField delegate method:

- (void)textDidChange:(NSNotification *)notification;
like image 36
trojanfoe Avatar answered Oct 10 '22 03:10

trojanfoe