集合视图按钮操作(Cocoa、Xcode)

Collection View Button Action (Cocoa, Xcode)

在 XIB 文件中,我有一个包含按钮的集合视图。从 Nib 唤醒时,我定义了几个具有不同图像的按钮。所以应用程序基本上看起来像一个取景器,但还没有执行任何操作。

我现在想做的是,当按下每个按钮时,都会打开一个不同的文件(我使用文件管理器方法)。我可以在非集合视图类型的应用程序中轻松地做到这一点,但是当使用集合视图时,我不确定如何为每个按钮附加不同的操作。

这就是我所拥有的,但是当我希望每个按钮打开不同的 pdf 时,它会为每个按钮打开相同的 pdf.pdf。

@implementation AppController
-(void) awakeFromNib {


MyButton *Button1 = [[MyButton alloc] init];
Button1.image = [NSImage imageNamed:@"img1"];


MyButton *Button2 = [[MyButton alloc] init];
Button2.image = [NSImage imageNamed:@"img2"];

MyButton *Button3 = [[MyButton alloc] init];
Button3.image = [NSImage imageNamed:@"img3"];

_modelArray = [[NSMutableArray alloc] init];
[controller addObject:Button1];
[controller addObject:Button2];
[controller addObject:Button3];}

- (IBAction)OpenCVFile:(id)sender {


NSFileManager *fileManagerCv = [[NSFileManager alloc] init];
NSString *filePath = @"Users/Tom/pdf.pdf";

if ([fileManagerCv fileExistsAtPath:filePath]) {
    NSLog(@"File exists");
    [[NSWorkspace sharedWorkspace]openFile:filePath withApplication:@"Finder"];}
else {
    NSLog(@"File does not exist");

}
}

有人能帮忙吗? 任何帮助将不胜感激。

使用绑定

首先,向您的模型 class 引入一个 属性 指向控制器。

例如,一个非常简单的模型 class 将是:

@interface ModelData : NSObject

@property NSString *name;
@property id controller;

@end

@implementation ModelData
@end

初始化您的集合视图 content:

// In the controller
ModelData *data1 = [ModelData new];
data1.name = @"Apple";
data1.controller = self;

ModelData *data2 = [ModelData new];
data2.name = @"Boy";
data2.controller = self;

[self.collectionView setContent:@[data1, data2]];

在界面构建器中,select 原型中的按钮 Collection View Item,导航到 Bindings Inspector,为 Argument 创建绑定,然后Target:

  • 对于 Argument,将 Bind to 设置为 Collection View Item,然后将 Model Key Path 设置为模型中的任何 属性 class,您可以使用它来唯一标识按钮(例如 representedObject.name),并将 Selector Name 设置为您的操作方法的签名,例如 buttonClicked:.

  • 对于 Target,将 Bind to 设置为 Collection View Item,然后将 Model Key Path 设置为指向您的控制器的内容 class (实现action方法的地方),设置Selector Name同上

设置这两个绑定后,您在控制器中的操作方法 class 将使用您在单击按钮时指定的参数进行调用。

// In the controller
- (IBAction)buttonClicked:(id)anArg {
    NSLog(@"%@", anArg);
}