【问题标题】:Change background image of a button programmatically cocoa obj-c以编程方式更改按钮的背景图像可可 obj-c
【发布时间】:2020-03-07 14:48:26
【问题描述】:

我正在创建 NSCollection 视图(在 Cocoa 中),其中包含许多大小和外观相同的按钮,除了它们的图标(或者您可能称它们为背景图像)。

在我的 xib 文件中,我将按钮绑定到集合视图(模型键路径:representedObject.foto),并且数组控制器具有 MyButton 和 Keys 类:foto。

我使用 NSImage 属性创建了 My Button 类 - 这是正确的方法吗? 如何在 AppController.m 中设置我的项目中的图像,以便在运行我的应用程序时显示在按钮上?

其他一切都应该没问题,因为我之前创建了带有标签的 NSCollectionView 并且它有效。

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

【问题讨论】:

    标签: xcode image cocoa nsbutton nscollectionview


    【解决方案1】:

    您的图片在您的项目中位于何处?如果它在 .xcasset 文件中,那么您可以使用以下方式设置图像:

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

    You can learn about storing images in assets here。我建议使用这些资产,因为它可以让您将项目中可能使用的所有图像保持井井有条,并且有助于减少维护多种分辨率图像的麻烦。

    【讨论】:

    • 然后,当绑定我的按钮时,我应该绑定到集合视图项,模型键路径:representedObject.image?
    • 我相信是的。还是试试吧
    • 我将它绑定在图像部分而不是参数下,它可以工作!!!我简直不敢相信!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2020-05-15
    • 2012-07-11
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多