gpt4 book ai didi

objective-c - 在两个类中调用IBAction方法

转载 作者:行者123 更新时间:2023-12-03 17:32:16 24 4
gpt4 key购买 nike

我试图在两个类中调用 IBAction 方法,每当单击我在界面生成器中创建的按钮时就会调用该方法。我真正想要发生的是,只要单击按钮,就会出现 NSRect,但按钮和我希望 NSRect 出现的位置位于单独的 View 中,因此按钮位于 View A 中,而矩形的目标位于 View B。我尝试使用 NSNotificationCenter 执行此操作,但没有成功。

最佳答案

您缺少MVC中的C。 Cocoa 使用模型- View - Controller 设计模式,而您似乎缺少 Controller 。

您应该创建一个 Controller 类(可能是 NSWindowController 的子类,以便它负责窗口),该类实现一个操作方法,例如 -buttonPressed: ,它是连接到您的按钮。 Controller 应该管理模型(在本例中是矩形代表的任何模型),以便当您按下按钮时,模型会更新。然后 Controller 应该让您的矩形 View 自行重绘。

应该设置您的矩形 View ,以便它实现数据源模式(请参阅 NSTableView 数据源实现以获得一个很好的示例),以便它知道绘制矩形的数量和位置。如果您将 Controller 设置为 View 的数据源,则您的 View 不需要了解有关模型的任何信息。

您的矩形 View 应该设置如下:

矩形 View .h: @协议(protocol)矩形 View 数据源;

@interface RectangleView : NSView
@property (weak) id <RectangleViewDataSource> dataSource;
@end

//this is the data source protocol that feeds the view
@protocol RectangleViewDataSource <NSObject>
- (NSUInteger)numberOfRectsInView:(RectangleView*)view;
- (NSRect)rectangleView:(RectangleView*)view rectAtIndex:(NSUInteger)anIndex;
@end

矩形 View .m:

@implementation RectangleView
@synthesize dataSource;

- (void)drawRect:(NSRect)rect
{
//only draw if we have a data source
if([dataSource conformsToProtocol:@protocol(RectangleViewDataSource)])
{
//get the number of rects from the controller
NSUInteger numRects = [dataSource numberOfRectsInView:self];
for(NSUInteger i = 0; i < numRects; i++)
{
NSRect currentRect = [dataSource rectangleView:self rectAtIndex:i];
//draw the rect
NSFrameRect(currentRect);
}
}
}
@end

您可以将 Controller 指定为 View 的数据源,并使其实现 RectangleViewDataSource 协议(protocol)方法。

Controller 看起来像这样:

YourController.h:

#import "RectangleView.h"

@interface YourController : NSWindowController <RectangleViewDataSource>
@property (strong) NSMutableArray* rects;
@property (strong) IBOutlet RectangleView *rectView;

- (IBAction)buttonPressed:(id)sender;

@end

YourController.m:

@implementation YourController
@synthesize rects;
@synthesize rectView;

- (id)init
{
self = [super init];
if (self)
{
rects = [[NSMutableArray alloc] init];
}
return self;
}


- (void)awakeFromNib
{
//assign this controller as the view's data source
self.rectView.dataSource = self;
}

- (IBAction)buttonPressed:(id)sender
{
NSRect rect = NSMakeRect(0,0,100,100); //create rect here
[rects addObject:[NSValue valueWithRect:rect]];
[self.rectView setNeedsDisplay:YES];
}

//RectangleViewDataSource methods
- (NSUInteger)numberOfRectsInView:(RectangleView*)view
{
return [rects count];
}

- (NSRect)rectangleView:(RectangleView*)view rectAtIndex:(NSUInteger)anIndex
{
return [[rects objectAtIndex:anIndex] rectValue];
}


@end

关于objective-c - 在两个类中调用IBAction方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8264078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com