1

drawRect メソッドをトリガーするために、NSTimer セレクターで [self setNeedsDisplay:YES] を呼び出そうとしました。

最初に、NSTimer の初期化コードをボタン関数に入れました。

-(IBAction)buttonPush:(id)sender
{
   myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
    target:self
  selector:@selector(myTimerAction:)
  userInfo:nil
  repeats:YES];
}

-(void)myTimerAction:(NSTimer *) timer
{  
[self setNeedsDisplay:YES];
} 

「setNeedsDisplay」は通常どおり呼び出されますが、drawRect 内のコードは呼び出されません。

- (void)drawRect:(NSRect)dirtyRect 
{
NSLog(@"drawRect");
}

次に、NSTimer の初期化コードを "- (id)initWithFrame:(NSRect)frame" に移動しようとしましたが、すべて正常に動作しました。(drawRect は 1 秒ごとに正しく呼び出されます)。

上記の2つの方法の違いは何ですか? ボタンでタイマーをトリガーしたい場合はどうすればよいですか?

4

2 に答える 2

1

そのコードはどのクラスにあるのでしょうか。buttonPush :アクションはコントローラー内にあると思いますよね?

もしそうなら、あなたは持っているべきです:

-(void)myTimerAction:(NSTimer *) timer
{
  [[self view] setNeedsDisplay:YES];
}

setNeedsDisplay: はNSViewControllerではなくNSViewのメソッドであるためです。

(ところで、おそらくinitWithFrame:内に配置すると機能する理由は、それがNSViewイニシャライザであるためです。コードをそこに移動すると、 myTimerAction:メソッドも移動していると推測しています。これには「 self」がありますビューを正しく参照します。)

于 2011-02-04T20:19:51.937 に答える
0

Since it works when you use initWithFrame:, the problem is probably that buttonPush: isn't hooked up correctly. Try setting a breakpoint in buttonPush: an see if it is actually called when you click the button.

于 2011-02-10T11:07:19.037 に答える