5

Cocoa でプログラムを作成する方法を学んでいます。ウェブカメラからビデオを記録するサンプル Apple アプリケーションを使用しています。キーの押下をキャプチャしてビデオを開始および停止したいと思います。keydown イベントをオーバーライドしようとしましたが、NSObject. この種のイベントをどのように処理できますか?

アプリケーションのクラスはクラスを拡張しますNSObject

これはコードです:

- (void)keyDown:(NSEvent *)event {
  NSLog(@"Hi there");
  NSString *characters = [event characters];
  if ([characters length]) {
    switch ([characters characterAtIndex:0]) {
      case NSUpArrowFunctionKey:
      NSLog(@"Key UP");
      break;
    }
  }
}
4

3 に答える 3

7

Keydown イベントをオーバーライドしようとしましたが、NSObject では不可能であると読みました。

正しい。レスポンダのみがイベントに応答できます。

この種のイベントをどのように処理できますか?

レスポンダーを実装します。NSWindow または NSWindowController のサブクラス化は機能します。実際のウィンドウまたはウィンドウ コントローラーをサブクラスのインスタンスにするようにしてください。

Cocoa のドキュメントでさらに説明されています。

アプリケーションのクラスは NSObject クラスを拡張します。

なんで?通常、アプリケーション バンドルの主要なクラスは NSApplication またはそのサブクラスですが、NSApplication をサブクラス化する正当な理由はあまりありません。

PS: MacOS プログラミングを学び始めるのに最適な本は何ですか?

私自身は Hillegass の本からは学びませんでしたが (私は Apple のドキュメントに固執しました)、これは非常に人気のある推奨事項であり、読んだことがあります。

于 2009-07-17T15:13:12.097 に答える
4

From the Cocoa Event-Handling Guide - The Responder Chain:

The responder chain is a linked series of responder objects to which an event or action message is applied. When a given responder object doesn’t handle a particular message, the object passes the message to its successor in the chain (that is, its next responder).

When you press a key the window receives the keyDown event. Then it dispatches the event to the first responder, that usually is the control with a blue bezel around its border (try to click on the address field in Safari or Firefox, when it's blue-bezeled then it has first-responder status).

If the first responder does not eat the keypress (the Safari address field does eat it when it displays a character) then it passes it down the responder chain to the next responder in the view hierarchy, then to the window and to the window controller as you can see in the Guide. (Take care that the action responder is another story.)

So you have to implement the keyDown: on a view of your window or in the window itself, if it has no views that eat events. The simplest way to test is to override the keyDown: method of an empty window

To put your hands into the inner workings you can even try overriding the sendEvent: method of a window. sendEvent: dispatches the events to the views of the window, and from there you can for example log all the events managed by the window.

于 2009-07-17T23:29:12.220 に答える
4

NSWindow または NSWindowController のサブクラス化は機能します。

同様に、NSView をサブクラス化し、そのイベント処理メソッドをオーバーライドできます。

MacOS プログラミングを学び始めるのに最適な本は何ですか?

Learn Objective-C on the Mac by Dalrymple は非常に簡単で、十分な基本事項をカバーしており、短時間で十分な速さで作業を開始できます。Xcode や Interface Builder から OOP や Objective-C の実践まで、あらゆることに触れています。初心者 (IMHO) にとって特に役立つのは、ソース ファイルの編成と Foundation キットの章です。

頑張ってください!

于 2009-12-06T10:19:15.250 に答える