我查看了其他代表问题,但没有任何好的现有答案。一切都应该正确设置,我可以看到我的滑块将更改日志中的值。由于某种原因,当我从 squareView 调用委托函数 numberOfSquaresInSquareView() 时,它永远不会触发,并且 squareView 委托调用仅返回 nil。我知道我已经相当接近了,因为这与我发现的一些课程非常匹配,但我认为我错过了一些东西。 changeSquareCount() 有效,我可以在日志中看到它保存了该值。
squareView.h
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@class SquareView;
@protocol SquareViewDelegate <NSObject>
- (NSNumber *)numberOfSquaresInSquareView:(SquareView *)squareView;
@end
@interface SquareView : NSView
@property (nonatomic, weak) id<SquareViewDelegate> delegate;
@end
NS_ASSUME_NONNULL_END
squareView.m
#import "SquareView.h"
@implementation SquareView
@synthesize delegate;
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
NSLog(@"drawing rect");
[[NSColor redColor]set];
//NSNumber *num = ; //cound pass in nil, dont matter
NSLog(@"squares to draw: %@", [delegate numberOfSquaresInSquareView:self]);
// Drawing code here.
}
@end
AppController.h
#import <Foundation/Foundation.h>
#import "SquareView.h"
//@class SquareView;
NS_ASSUME_NONNULL_BEGIN
@interface AppController : NSObject <SquareViewDelegate>
@property (retain) IBOutlet SquareView *squareView;
- (IBAction)changeSquareCount:(id)sender;
@end
NS_ASSUME_NONNULL_END
AppController.m
#import "AppController.h"
@implementation AppController
{
NSNumber *_squareCount;
}
@synthesize squareView = _squareView;
- (void)awakeFromNib
{
[_squareView setDelegate:nil];
_squareCount = @(10);
[_squareView setNeedsDisplay:YES];
}
- (void)changeSquareCount:(id)sender
{
_squareCount = @([sender intValue]);
NSLog(@"square count stored: %@",_squareCount);
[_squareView setNeedsDisplay:YES];
}
-(NSNumber *)numberOfSquaresInSquareView:(SquareView *) squareView
{
NSLog(@"triggering numberOfSquaresInSquareView");
return _squareCount;
}
@end
delegate
必须“保留”某处才能使其发挥作用。正如我在这里看到的,SquareView
是AppController
的子视图,delegate
的工作方式与SquareView <-> AppController
类似。在这种情况下,这是一种回调。但是,您将其分配给 nil
[_squareView setDelegate:nil]
它应该是:
_squareView.delegate = self;
这样,每次调用 SquareView 中的
drawRect
时,都会触发 AppController 中的 numberOfSquaresInSquareView
,在这种情况下,它会打印出来
要绘制的方块:10