I have a view based table with a custom cell view. Inside this custom cell view, I have a custom NSButton that acts like a check box (it toggles a custom image on and off). This part works well. The images toggle on and off perfectly.
What I want to do is associate the custom button in the row with the actual row in the table. When I check/click the button it will highlight the the corresponding row and then perform an action on the row in which the check box/ button is situated. For example, removing the row from the table when the NSButton is clicked.
My custom NSButton is implemented as follows:
Header file:
#import <Foundation/Foundation.h>
@interface CustomCheckButton : NSButton {
BOOL _checked;
}
@property (nonatomic, setter=setChecked:) BOOL checked;
-(void) setChecked:(BOOL) check;
@end
Implementation:
#import "CustomCheckButton.h"
@implementation CustomCheckButton
@synthesize checked = _checked;
-(id) init
{
if( self=[super init] )
{
self.checked = NO;
[self setTarget:self];
[self setAction:@selector(onCheck:)];
}
return self;
}
-(void) awakeFromNib
{
self.checked = NO;
[self setTarget:self];
[self setAction:@selector(onCheck:)];
}
-(void) setChecked:(BOOL) check
{
_checked = check;
if( _checked )
{
NSImage* img = [NSImage imageNamed:@"check_on.png"];
[self setImage:img];
[self setState:NSOnState];
}
else
{
NSImage* img = [NSImage imageNamed:@"check_off.png"];
[self setImage:img];
[self setState:NSOffState];
}
}
-(void) onCheck:(id) sender
{
self.checked = !_checked;
NSLog(@"A check box was pressed");
}
@end
The current solution does not associate the button with the row at all. When I sort the rows, for example, the selected image is not linked to the row and often stays in the same place within the table, even though a different row was selected.
Any help on this would be greatly appreciated.
How about adding a delegate field and setting it with a custom initializer? Or you could add it as a property and set it after calling alloc init. This can be done in 2 ways: via IB or programmatically.
If you want to do it programmatically, you’ll need to do a couple of things:
So let’s look at the class that has a
UITableViewelement in it. Assuming this class is also theUITableViewDelegateandUITableViewDataSource, it will have to have an implementation of the data source methodwhich returns a cell at a given indexPath. Here, you could instantiate your custom cell and in that, add a custom button and set it’s delegate to the cell itself, by adding this to your code:
in CustomCheckButton.h:
in CustomCheckButton.m
in the table view data source method:
This might seem like a big task, but you can do it in interface builder too, assuming you have a xib for your custom cell class. If you do, just open the xib. You’ll probably have a button on it already; change it’s class to your own
CustomCheckButtonand you’ll be able to set its delegate property like you would normally, with ctrl-drag from the button to the cell.Hope this helps!