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

时间:2015-05-31 10:03:58

标签: xcode cocoa button collectionview

在XIB文件中,我有一个包含按钮的集合视图。在从Nib醒来时,我已经定义了几个具有不同图像的按钮。因此,应用程序基本上看起来像一个查找程序,但尚未执行任何操作。

我现在要做的是,当按下每个按钮时,会打开另一个文件(我使用filemanager方法)。我可以在非集合视图类型应用程序中轻松完成此操作,但在使用集合视图时,我不确定如何为每个按钮附加不同的操作。

这就是我所拥有的,但当我希望每个按钮打开不同的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");

}
}

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

1 个答案:

答案 0 :(得分:1)

使用绑定

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

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

@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]];

在界面构建器中,选择原型Collection View Item中的按钮,导航到 Bindings Inspector ,为ArgumentTarget创建绑定:

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

  • 对于Target,将Bind to设置为Collection View Item,然后将Model Key Path设置为指向控制器类的位置(执行操作方法的位置) ,并将Selector Name设置为与上面相同。

enter image description here enter image description here

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

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