Cocoa:接受和响应击键 [英] Cocoa: Accepting and responding to keystrokes

查看:158
本文介绍了Cocoa:接受和响应击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,大家,我是一个新手,我有我的期望将是一个很容易的问题回答。为了学习一点关于事件处理和绘图,我试图写一个程序,绘制一个黑色的矩形,在每次用户点击'c'键时增加长度。到目前为止,它只是在蓝色背景上绘制一个黑色矩形,而不响应按键。这是我到目前为止:

Hey everyone, I'm a newbie and I have what I anticipate will be a pretty easy question to answer. In order to learn a bit about event handling and drawing, I'm attempting to write a program that draws a black rectangle that increases in length every time the user hits the 'c' key. So far it just draws a black rectangle on a blue background without responding to keystrokes. Here is what I have so far:

Input.h

#import <Cocoa/Cocoa.h>


@interface Input : NSView {

 int length;

}

- (void)keyDown:(NSEvent *)theEvent;
@end

Input.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



复制keydown方法从Cocoa在一个坚果,顺便说一句。不用说,我真的不明白。我必须在IB中进行连接,以使程序识别击键?基本上,如果有人可以帮助我让这个程序工作,我会喜欢它,因为我还没有得到任何响应击键。

I copied the keyDown method from Cocoa in a Nutshell, by the way. Needless to say, I don't really understand it. Do I have to make connections in IB in order to get the program to recognize keystrokes? Basically, I would love it if somebody could help me to get this program to work, because as of yet I have not gotten anything to respond to keystrokes.

这里的< a href =http://proquest.safaribooksonline.com/0-596-00462-1/cocoaian-CHP-3-SECT-9 =nofollow noreferrer>可口可乐

推荐答案

IIRC,接收击键,您的视图需要成为第一个响应者。它应该工作,如果你添加像这样的方法:

IIRC, to receive keystrokes your view needs to become first responder. It should work if you add something like these methods:

- (BOOL) acceptsFirstResponder
{
    return YES;
}
- (BOOL) resignFirstResponder
{
    return YES;
}
- (BOOL) becomeFirstResponder
{
    return YES;
}

(你也可以做其他的东西, )

(You can do other stuff in them too, of course, if appropriate.)

更新:。您还需要将视图标记为需要重绘。添加:

Update: You also need to mark your view as needing to be redrawn. Add:

[self setNeedsDisplay:YES];

到您的事件处理程序。在开始时添加一个日志消息可能是一个好主意,以便您可以看到该方法是否被调用:

To your event handler. And it's probably a good idea to add a log message at the beginning as well, so that you can see whether the method is getting called:

NSLog(@"keyDown [%@]", [theEvent characters]);

这篇关于Cocoa:接受和响应击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆