Change background image of a button programaticall

2019-09-06 12:08发布

问题:

I am creating NSCollection View (in Cocoa) with many identical buttons in size and appearance, except for their icons (or you could probably call them Background Images).

In my xib file I have the button binded to the Collection View (Model key path: representedObject.foto) and the Array Controller has class of MyButton and Keys: foto.

I created My Button class with NSImage property - is this the right way to do it? How do I set an Image that I have in my project in AppController.m so that it appears on the button when running my app?

Everything else should be fine, because I have previously create NSCollectionView with Labels and it worked.

MyButton.h

#import <Cocoa/Cocoa.h>
@interface MyButton : NSButton
@property(retain, readwrite) NSImage *foto;
@end  

MyButton.m

#import "MyButton.h"
@implementation MyButton
@end

AppController.h

@interface AppController : NSObject {IBOutlet NSArrayController *controller;}
@property (strong) NSMutableArray *modelArray;
@end

AppController.m

#import "AppController.h"
#import "MyButton.h"
@implementation AppController

- (void) awakeFromNib {
MyButton *FirstOne = [[MyButton alloc] init];
//FirstOne.foto = ???

_modelArray = [[NSMutableArray alloc] init];
[controller addObject:FirstOne];}

@end

回答1:

Where is your image located in your project? If its in an .xcasset file, then you can set the image with:

FirstOne.image = [NSImage imageNamed:@"StatusBarIcon"];

You can learn about storing images in assets here. I would recommend using these assets as it allows you to keep all the images that you may use in your project organised, and it helps reduce the hassle of maintaining images for multiple resolutions.