大家好,我是一个新手,我预计这将是一个很容易回答的问题。为了学习一些关于事件处理和绘图的知识,我正在尝试编写一个程序,该程序绘制一个黑色矩形,每次用户点击“c”键时,该矩形的长度都会增加。到目前为止,它只是在蓝色背景上绘制一个黑色矩形,而不响应击键。这是我到目前为止所拥有的:
输入.h
#import <Cocoa/Cocoa.h>
@interface Input : NSView {
int length;
}
- (void)keyDown:(NSEvent *)theEvent;
@end
输入.m
#import "Input.h"
@implementation Input
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
length = 10;
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
//set variables
NSRect r1;
NSBezierPath *bp;
// set background color
[[NSColor blueColor] set];
NSRectFill(dirtyRect);
//set color to black & draw r1
[[NSColor blackColor] set];
r1 = NSMakeRect(1, 1, length, 10);
bp = [NSBezierPath bezierPathWithRect:r1];
[bp fill];
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString *key = [theEvent characters];
if ( [key isEqualToString:@"c"] ) {
length += 10;
}
}
@end
顺便说一句,我从 Cocoa 中复制了 keyDown 方法。不用说,我真的不明白。我是否必须在 IB 中建立连接才能让程序识别击键?基本上,如果有人可以帮助我让这个程序正常工作,我会很高兴的,因为到目前为止我还没有得到任何响应击键的东西。