Add/remove rows to/from NSTableView in Objective-C

元气小坏坏 提交于 2019-11-30 04:37:05

问题


I'm making a simple Todo application in Cocoa. I have added a class (and an NSObject to the XIB) MATodoController:

MATodoController.h

#import <Cocoa/Cocoa.h>


@interface MATodoController : NSObject
{
    IBOutlet NSTableView *table;
}

- (IBAction)addItem:(id)sender;
- (IBAction)removeItem:(id)sender;

@end

MATodoController.m

#import "MATodoController.h"


@implementation MATodoController

- (void)addItem:(id)sender
{

}

- (void)removeItem:(id)sender
{

}

@end

I have an outlet 'table' to an NSTableView and two actions 'addItem' and 'removeItem' called by button clicks.

Is there a way (ofcourse there is a way)How can I add new rows / remove selected rows to and from an NSTableView (users can select multiple rows at once)?

Thanks in advance.

Oh, one more thing: The NSTableView has only one column (which consists of checkboxes).


回答1:


In Cocoa, you don't really add/remove rows to a NSTableView directly. In your controller, you might want to adopt the NSTableDataSource protocol, which has 2 important methods you need to implement in order to get this working:

- (int) numberOfRowsInTableView:(NSTableView *)aTableView
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex

These methods will respond to messages the table view sends to it's data source (configured in Interface Builder) in order to populate the table with rows of data. In these method implementations, you will have to return the information that the method requires (the number of rows; the value of a cell in a particular row) by querying whatever data store you've worked out.

Your addItem and removeItem methods will also need to store/delete row data (in whatever representation you've concocted). You might create a new class that represents each row and store them in an NSMutableDictionary, for instance.

Besides Apple's docs, here's a good tutorial for this task.

Good luck!




回答2:


With Cocoa, the easiest way to do this is with bindings. Create an NSArrayController, linked to an instance of NSMutableArray, and bind the NSArrayController to the NSTableView.

CocoaDev gives a good overview of the procedure. You can also read Apple's documentation, and CocoaDev's excellent article on bindings.



来源:https://stackoverflow.com/questions/1306737/add-remove-rows-to-from-nstableview-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!